keeping variable alive in a javascript function

后端 未结 2 1551
后悔当初
后悔当初 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:32

    I believe the scope of your variable is too "low"; by defining the variable within the function, either as a parameter or explicitly as a var, it is only accessible within the function. In order to achieve what you're after, you can either implement the variable outside the scope of the function, at a more global evel (not recommened really).

    However, after re-reading your question, it's slightly miss-leading. Would you not want to return state regardless of the current? I think you might be after something like so:

    var state;
    function plan_state(current)
    {
        if (current != '' && current != state)
        {
            state = current;
        }
        return state;
    } 
    

    Alternative object structure:

    function StateManager(state)
    {
        this.state = state;
    
        this.getState = function(current)
        {
            if (current != '' && current != this.state)
            {
                this.state = current;
            }
            return this.state;
        }
    }
    
    // usage
    var myStateManager = new StateManager("initial state here");
    var theState = myStateManager.getState("some other state");
    

提交回复
热议问题