I want the variable i to be a counter, but it is being initialized to 100 each time.
How do I call myFunction().f() directly?
function myFunction() {
var i=100;
function f() {
i=i+1;
return i;
}
return f(); // with parenthesis
};
var X = myFunction();
console.log(X);
X = myFunction();
console.log(X);
You can’t call
fdirectly. It is wrapped in a closure, the point of which is to close over all the local variable. You have to expose it to the outside ofmyFunction.First:
Then just call X, as you’ll have assigned a function to it.