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. So how does one maintain a function variable's value between function calls?
I tried the obvious, but myvar is always undefined at the 开发者_如何学Cstart of the function:
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?
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
. Because of the anonymous function wrapper, the variable cannot be modified from elsewhere.
You can store the value on the function by using arguments.callee
as a reference to the current function:
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 (e.g. 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.
}
})();
精彩评论