2

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 start 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?

1
  • 1
    Are you missing a closing parenthesis Commented Oct 2, 2011 at 8:55

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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).

Comments

4

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.
  }
})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.