将变量保存在JavaScript函数中 [英] keeping variable alive in a javascript function

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

问题描述

我想在一个函数中放置一个变量
这个变量将根据用户交互改变状态

 函数plan_state(current){
if(current!=''){
state = current;
}
else {
返回状态;


$ / code>

当文档加载时,我会调用pl​​an_state('me' );

当某些事情发生时,我可能会调用pl​​an_state('loved')

这个问题,我跑一个函数,并希望检查当前状态。

  alert(plan_state()); 

我得到undefined回来,至少应该是'我',因为我设置了这个onload。



我做错了什么?

解决方案

函数isn'因为状态变量是在函数内声明的,所以只存在于函数调用的生命周期中。一个简单的解决方案是在函数之外全局声明变量。这是不好 < a href =https://stackoverflow.com/questions/5787351/what-is-so-bad-about-global-variables>不良 错误 错误

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

  var stateModule =(function(){
var state; // Private Variable

var pub = {}; // public object - returned at module end

pub.changeState = function(newstate){
state = newstate;
};

pub.getState = function(){
return状态;
}

返回pub; //向外暴露
}());

so stateModule.changeState(newstate); 设置状态



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


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?

解决方案

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

这篇关于将变量保存在JavaScript函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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