用JavaScript封闭

时间:2011-09-06 15:06:13

标签: javascript closures

我希望变量i是一个计数器,但它每次都被初始化为100

如何直接致电myFunction().f()

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

2 个答案:

答案 0 :(得分:9)

您无法直接致电f。它被封装在一个闭包中,其关键是要关闭所有局部变量。您必须将其公开到myFunction的外部。

首先:

return f; //(); // withOUT parenthesis

然后只需调用X,因为你已经为它分配了一个函数。

var X = myFunction();
X();

答案 1 :(得分:2)

此示例将返回101和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

如果你需要致电myFunction().f()那将是一个毫无意义的关闭:

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?