이 예는 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?
폐쇄의 목적이다 함수 내에서 변수 범위를 유지하지만 함수가 반환 된 후에도 변수는 상태를 유지합니다. 죄송합니다. 이것은 "폐쇄 목적은 무엇입니까?"에 대한 다른 사람의 의견에 대한 회신이었습니다. –