在 javascript 函数中保持变量处于活动状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10452604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:21:42  来源:igfitidea点击:

keeping variable alive in a javascript function

javascriptfunctionvariablescall

提问by Daniel Hunter

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

当文档加载时,我调用 plan_state('me');

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

当某些事情发生时,我可能会调用 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.

我回来了未定义,至少应该是“我”,因为我设置了这个 onload。

what am i doing wrong?

我究竟做错了什么?

回答by reach4thelasers

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

该函数不是有状态的,因为状态变量是在函数内部声明的,因此仅在函数调用的生命周期内存在。一个简单的解决方案是在函数外部全局声明变量。这是坏的

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();获得状态

回答by Richard

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

我相信您的变量范围太“低”;通过在函数内将变量定义为参数或显式定义为 a var,它只能在函数内访问。为了实现您所追求的目标,您可以在函数范围之外以更全局的方式实现变量(实际上并不推荐)。

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

但是,在重新阅读您的问题后,它略有误导。你不想回来state不管current吗?我想你可能会追求这样的事情:

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