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);
asked Sep 6, 2011 at 15:06
Phillip Senn
47.8k92 gold badges263 silver badges381 bronze badges
-
The purpose of closure is to keep variables scoped within the function, and yet they maintain their state after the function returns. Oops. This was in reply to someone else's comment about "What's the purpose of closure?"Phillip Senn– Phillip Senn2011年09月06日 15:15:44 +00:00Commented Sep 6, 2011 at 15:15
2 Answers 2
You can't call f directly. 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 of myFunction.
First:
return f; //(); // withOUT parenthesis
Then just call X, as you'll have assigned a function to it.
var X = myFunction();
X();
answered Sep 6, 2011 at 15:07
Quentin
949k137 gold badges1.3k silver badges1.4k bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Phillip Senn
Thanks Quentin! When I console.log(X()) a second time, it still returns 101.
Phillip Senn
OK, I got it! Thanks! (I was assigning X = myFunction() a second time as well, which was wrong).
This example would return 101 and 102: Be sure to try it.
function myFunction() {
var i=100;
function f() {
i=i+1;
return i;
}
return f; // without any parenthesis
};
var X = myFunction();
// X is a function here
console.log(X());
// when you call it, variable i gets incremented
console.log(X());
// now you can only access i by means of calling X()
// variable i is protected by the closure
If you need to call myFunction().f() that will be a pointless kind of closure:
function myFunction() {
var i=100;
function f() {
i=i+1;
return i;
}
return {x : f}
};
var X = myFunction().x();
// X now contains 101
var X = myFunction().x();
// X still contains 101
// pointless, isn't it?
answered Sep 6, 2011 at 15:11
sanmai
31.2k12 gold badges72 silver badges76 bronze badges
3 Comments
Phillip Senn
This returns 101 two times. I would like it to return 101, 102.
Phillip Senn
Well, I'm trying to understand the correct way to use closure. I don't want to learn something that would be a pointless kind of closure.
Phillip Senn
Oh, I see... You were showing me both the right way AND the wrong way to do it...
lang-js