Phillip Senn
Phillip Senn

Reputation: 47663

closure in JavaScript

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);

Upvotes: 3

Views: 203

Answers (2)

sanmai
sanmai

Reputation: 30951

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?

Upvotes: 2

Quentin
Quentin

Reputation: 944555

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();

Upvotes: 9

Related Questions