在 javascript 函数中保持变量处于活动状态的问题 [英] Problem keeping variable alive in a javascript function

查看:31
本文介绍了在 javascript 函数中保持变量处于活动状态的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在函数中放置一个变量.此变量将根据用户交互改变状态.例如:

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

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

当文档加载时我调用plan_state('me'),当某些事情发生时我可能调用plan_state('loved').当我运行一个函数并想检查当前状态时出现问题:

When the document loads I call plan_state('me'), and when certain things happen I may call plan_state('loved'). The problem occurs when I run a function and want to check the current state:

alert(plan_state());

我返回了 undefined,但值应该是 'me',因为我之前在文档加载时设置了这个值.

I get undefined back, but the value should be 'me' as I previously set this value on document load.

我做错了什么?

推荐答案

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

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.

更好的方法是使用模块模式.如果您认真对待 javascript 开发,这是学习的基本模式.它通过内部(私有变量)启用状态,并公开许多用于更改或获取状态的方法或函数(如面向对象编程)

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"); 设置状态

and var theState = stateModule.getState(); 获取状态

这篇关于在 javascript 函数中保持变量处于活动状态的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆