維基百科中的解釋,閉包存儲(chǔ)了函數(shù)以及函數(shù)定義時(shí)的環(huán)境變量(自由變量)。
在談閉包的時(shí)候,有個(gè)概念需要說明一下:Scope Chain 作用域鏈。
Scope Chain
每個(gè)函數(shù)都有自己的作用域以及外部的作用域,甚至是全局的作用域。當(dāng)函數(shù)試圖訪問一個(gè)變量的時(shí)候,會(huì)現(xiàn)在這個(gè)函數(shù)的local env中查找。如果沒有,就到外部環(huán)境中查找。一層一層往外尋找,直到找到對(duì)應(yīng)的變量或者到達(dá)了global env還是沒有找到,那么這個(gè)變量就是undefined。
舉一個(gè)例子:
let txt = 'This is outsides.';
function log () {
let txt = 'This is insides.';
console.log(txt);
}
log();
// The output: This is insides.
輸出的結(jié)果是This is insides而不是This is insides.的原因就是,函數(shù)先從最內(nèi)層作用域開始尋找這個(gè)變量,一旦找到了就不在接著尋找了。
Use Case
緩存變量
當(dāng)你在閉包當(dāng)中訪問了外部變量的時(shí)候,這個(gè)變量會(huì)被添加到這個(gè)閉包當(dāng)中,即Execution Context。這種辦法能使得外部的一些臨時(shí)變量不會(huì)被當(dāng)做垃圾清理了。實(shí)現(xiàn)單例
其實(shí)這也是緩存變量的應(yīng)用。在代碼上:
class Earth(){...}
function TheEarth(){
let singleton = null;
return {
getEarth(){
if (singleton){ return singleton; }
createEarth();
return singleton;
}
createEarth(){ singleton = new Earth(); }
}
}
export default TheEarth();
然后,你就可以調(diào)用了:
import TheEarth from '../Earth';
TheEarth.getEarth()