在javascript函数中保持变量存活

时间:2022-01-12 00:10:26

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

当doc加载时我调用plan_state('me');

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

当某些事情发生时,我可以打电话给plan_state('喜欢')

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.

我得到了未定义的回复,至少应该是'我',因为我设置这个onload。

what am i doing wrong?

我究竟做错了什么?

2 个解决方案

#1


38  

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)

更好的方法是使用模块模式。如果你认真对待javascript开发,这是一个必不可少的模式。它通过内部(私有变量)启用状态,并公开许多方法或函数来更改或获取状态(如面向对象的编程)

    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

所以stateModule.changeState(“newstate”);设定国家

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

和var theState = stateModule.getState();获得国家

#2


1  

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).

我相信你的变量的范围太“低”;通过在函数中定义变量,无论是作为参数还是显式地作为var,它只能在函数内访问。为了实现你所追求的目标,你可以在函数范围之外实现变量,在更全局的范围内实现(不是真的推荐)。

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

#1


38  

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)

更好的方法是使用模块模式。如果你认真对待javascript开发,这是一个必不可少的模式。它通过内部(私有变量)启用状态,并公开许多方法或函数来更改或获取状态(如面向对象的编程)

    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

所以stateModule.changeState(“newstate”);设定国家

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

和var theState = stateModule.getState();获得国家

#2


1  

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).

我相信你的变量的范围太“低”;通过在函数中定义变量,无论是作为参数还是显式地作为var,它只能在函数内访问。为了实现你所追求的目标,你可以在函数范围之外实现变量,在更全局的范围内实现(不是真的推荐)。

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