Closure is when a function remembers and continues to access variables from outside its scope, even when the function is executed in a different scope.
一個函式能夠 access 其 scope 以外的變數,就稱為 closure (閉包)。
function greeting(msg) {
return function who(name) {
// the **who** function closes over the varaible *msg*,
// which is the parameter from the outer scope
console.log(`${ msg }, ${ name }`);
}
}
// calling greeting(...) create an instance of the inner function,
// and when the inner function is retured,
// its reference is assigned
// to the **hello** and **howdy** variable in the outer scope.
var hello = greeting('Hello');
var howdy = greeting('Howdy');
hello('Janet'); // Hello, Janet
hello('Alice'); // Hello, Alice
howdy('Sarah'); // Howdy, Sarah
// After finishing running these functions,
// the msg didn't go away since closure.
// Because the inner function instances are
// still alive ( assigned to hello and howdy ),
// their closures arer still preserving the msg variables.
再看一個例子,我覺得 closure 很像「雙心石滬」,variable 進得去出不來
function counter(step) {
var count = 0;
console.log(`Outer scope count ${ count }`);
return function increaseCount() {
// this closure close over the count variable,
// and it can actually observe or make updates to the count variable
count += step;
console.log(`Count: ${ count }`);
}
}
var increase1 = counter(1); // Outer scope count 0
var increase3 = counter(3); // Outer scope count 0
increase1(); // Count: 1
increase1(); // Count: 2
increase3(); // Count: 3
increase3(); // Count: 6
increase3(); // Count: 9
每當執行 increase1()
或者 increase3()
都是在呼叫increaseCount
,又因為 count
和 step
都被 close 了,所以它們的值會被 closure 保留、更新,closure 是 close variable 而不是其 value。
[ 參考 ]
-https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/get-started/ch3.md#closure