tags:

views:

64

answers:

4

Here's an easy one straight from the text book I can't seem to find.

I have a javascript function. I want it to contain a private variable which remembers its value between invocations.

Can someone jog my memory please.

+5  A: 

Create it using a closure:

function f() {
  var x = 0;
  return function() {return x++;};
}

Then use it as follows:

> g = f()
function () {return x++}
> g()
0
> g()
1
> g()
2
Max Shawabkeh
@OP: This is the correct way to do this. Be aware, though, that there is a cost involved: Every call to `f` creates a *new* function, which can have memory implications. You can't rely on implementations reusing the underlying code and just creating a new environment for it every time (and in fact, I don't think most do, from my informal experiments). So there's the trade-off, you can get a truly private variable, but at a memory cost. Not important if there won't be many of these, but significant if there will.
T.J. Crowder
A: 

Here is a truly private implementation

    (function() {

        var privateVar = 0;

        window.getPreviousValue = function(arg) {
            var previousVal = privateVar;
            privateVar = arg;
            return previousVal;
        }

    })()

    alert(getPreviousValue(1));
    alert(getPreviousValue(2));

Cheers

Sky Sanders
This won't create a *private* variable. It will be accessible from outside.
Max Shawabkeh
@max - i was clarifying that as you commented. thanks.
Sky Sanders
While it's always a good idea to remind people that functions are objects, your first example isn't even "privileged", it's completely public. *Anything* can look at `foo.privateVar`.
T.J. Crowder
@tj - Ok, you are right. I was incorrectly applying the priveledged concept to a property when it rightly relates to a method. thanks for that.
Sky Sanders
+1  A: 
 var accumulator = (function() {
    var accum = 0;

    return function(increment) {
       return accum += increment;
    }
 })();

 alert(accumulator(10));
 alert(accumulatot(15));

Displays 10 then 25.

AnthonyWJones
I guess it will display 10 and then 25?
Artem Barger
@Artem: Yes guess so to, I can program I just can't type.
AnthonyWJones
A: 

I am not sure if I understood correctly but maybe something like this would do the trick :

function Foo() {
  var x = "some private data";
  return {
   getPrivateData : function(){
      return x;
   }
  };
};

var xx = new Foo();
xx.getPrivateData();
miensol