How to call the function of calling a private variable between calls

Here is a simple one from a text that I cannot find.

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

Maybe someone runs through my memory.

+5
source share
4 answers

Create it using 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
+5
source
 var accumulator = (function() {
    var accum = 0;

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

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

Displays 10 and 25.

+1
source

    (function() {

        var privateVar = 0;

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

    })()

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

0

, , , - :

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

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

All Articles