简体   繁体   English

如何在调用之间维护JavaScript函数变量状态(值)?

[英]How to maintain JavaScript function variable states (values) between calls?

I am looking for getters and setters functionality but cannot rely on __defineGetter__ and __defineSetter__ yet. 我正在寻找getter和setter功能,但不能依赖__defineGetter____defineSetter__ So how does one maintain a function variable's value between function calls? 那么如何在函数调用之间维护函数变量的值?

I tried the obvious, but myvar is always undefined at the start of the function: 我尝试了显而易见的,但myvar在函数的开头总是未定义的:

FNS.itemCache = function(val) {
    var myvar;
    if( !$.isArray(myvar)
        myvar = [];
    if( val === undefined)
        return myvar;
    .. // Other stuff that copies the array elements from one to another without
       // recreating the array itself.
};

I could always put another FNS._itemCache = [] just above the function, but is there a way to encapsulate the values in the function between calls? 我总是可以在函数上方放置另一个FNS._itemCache = [] ,但有没有办法在函数之间封装函数中的值?

You can store the value on the function by using arguments.callee as a reference to the current function: 您可以使用arguments.callee作为对当前函数的引用,将值存储在函数中:

FNS.itemCache = function(val) {
    if( !$.isArray(arguments.callee._val)
        arguments.callee._val = [];
    if(val === undefined)
        return arguments.callee._val;
    .. // Other stuff that copies the array elements from one to another without
       // recreating the array itself.
};

However, this will break if the function is stored in a prototype and thus used by more than one object. 但是,如果函数存储在原型中并因此由多个对象使用,则会中断。 In this case you have to use a member variable (eg this._val ). 在这种情况下,您必须使用成员变量(例如this._val )。

this is a standard pattern for creating your static variable and for creating private members of an object 这是用于创建静态变量和创建对象的私有成员的标准模式

FNS.itemCache = (function() {
  var myvar;
  if( !$.isArray(myvar)
      myvar = [];
  return function(val) {
      if( val === undefined)
          return myvar;
         .. // Other stuff that copies the array elements from one to another without
         // recreating the array itself.
  }
})();

An alternative way to set a private variable is by wrapping the function definition in an anonymous function: 设置私有变量的另一种方法是将函数定义包装在匿名函数中:

(function(){
    var myvar;
    FNS.itemCache = function(val) {
        if( !$.isArray(myvar))
            myvar = [];
        if( typeof val == "undefined")
            return myvar;
        .. // Other stuff that copies the array elements from one to another without
           // recreating the array itself.
    };
})();

This way, myvar is defined in the scope of FNS.itemCache . 这样, myvar就在FNS.itemCache的范围内定义。 Because of the anonymous function wrapper, the variable cannot be modified from elsewhere. 由于匿名函数包装器,无法从其他地方修改变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM