keeping variable alive in a javascript function

假如想象 提交于 2019-12-03 03:43:45

问题


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

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

when the doc loads i call plan_state('me');

when certain things happen i may call plan_state('loved')

the problem, i run a function and want to check the current state..

alert(plan_state());

i get undefined back and at the very least is should be 'me' as i set this onload.

what am i doing wrong?


回答1:


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




回答2:


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");


来源:https://stackoverflow.com/questions/10452604/keeping-variable-alive-in-a-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!