keeping variable alive in a javascript function

后端 未结 2 1550
后悔当初
后悔当初 2020-12-23 10:55

I want to house a variable in a function This variable will change state depending on user interaction

function plan_state(current){
    if (current != \'\')         


        
2条回答
  •  温柔的废话
    2020-12-23 11:24

    The function isn't stateful because the state variable is declared inside the function and therefore only exists for the lifetime of the function call. An easy solution would be to declare the variable globally, outside the function. This is bad bad bad bad.

    A better approach is to use the module pattern. This is an essential pattern to learn if you're serious about javascript development. It enables state by means of internal (private variables) and exposes a number of methods or functions for changing or getting the state (like object oriented programming)

        var stateModule = (function () {
            var state; // Private Variable
    
            var pub = {};// public object - returned at end of module
    
            pub.changeState = function (newstate) {
                state = newstate;
            };
    
            pub.getState = function() {
                return state;
            }
    
            return pub; // expose externally
        }());
    

    so stateModule.changeState("newstate"); sets the state

    and var theState = stateModule.getState(); gets the state

提交回复
热议问题