Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 680
Phillip Senn Avatar asked Aug 02 '26 14:08

Phillip Senn


2 Answers

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();
like image 145
Quentin Avatar answered Aug 04 '26 03:08

Quentin


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?
like image 40
sanmai Avatar answered Aug 04 '26 02:08

sanmai