Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have function recall private variable between invocations

Tags:

javascript

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.

like image 460
John Mee Avatar asked Apr 18 '10 08:04

John Mee


1 Answers

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
like image 79
Max Shawabkeh Avatar answered Sep 30 '22 00:09

Max Shawabkeh