如何在调用之间维护JavaScript函数变量状态(值)?
问题描述:
我在寻找getter和setter的功能,但不能依赖于__defineGetter__
和__defineSetter__
。那么如何在函数调用之间维护函数变量的值?如何在调用之间维护JavaScript函数变量状态(值)?
我尝试了很明显,但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.
};
我随时可以把另一个FNS._itemCache = []
只是上面的函数,但有封装中的值的方法函数之间的调用?
答
的另一种方式设置为私有变量是由一个匿名函数包装函数定义的私有成员的标准模式:
(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.
};
})();
这样,myvar
被定义在FNS.itemCache
的范围内。由于匿名函数包装器,变量不能从其他地方修改。
答
可以通过使用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.
};
然而,如果功能被存储在一个原型,因此由一个以上的使用,这将破坏目的。在这种情况下,您必须使用成员变量(例如this._val
)。
答
这是创建静态变量,用于创建对象
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.
}
})();
您是否错过了右括号 – mowwwalker
是否需要保密? – David