這個例子會返回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?
閉合的目的是將變量作用域保留在函數中,但它們在函數返回後保持其狀態。哎呀。這是爲了回覆別人對「關閉的目的是什麼?」的評論。 –