3

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);
1
  • 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?" Commented Sep 6, 2011 at 15:15

2 Answers 2

9

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Quentin! When I console.log(X()) a second time, it still returns 101.
OK, I got it! Thanks! (I was assigning X = myFunction() a second time as well, which was wrong).
2

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?

3 Comments

This returns 101 two times. I would like it to return 101, 102.
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.
Oh, I see... You were showing me both the right way AND the wrong way to do it...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.