- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- JavaScript中什么是閉包
這篇文章給大家介紹JavaScript中什么是閉包,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
一 、詞法定義域 Lexical
Closure閉包是編程語(yǔ)言L(fǎng)exical Scoping的專(zhuān)有屬性,區別于dynamic scoping。即函數執行調用的是其在定義過(guò)程中的”變量定義域“,而非其在調用時(shí)候的變量定義域。
Javascript的函數的初始狀態(tài)不僅包括函數本體而且包括函數定義過(guò)程所在的定義域。
Like most modern programming languages, JavaScript uses lexical scoping. This means that functions are executed using the variable scope that was in effect when they were defined, not the variable scope that is in effect when they are invoked. In order to implement lexical scoping, the internal state of a JavaScript function object must include not only the code of the function but also a reference to the scope in which the function definition appears. This combination of a function object and a scope (a set of variable bindings) in which the function’s variables are resolved is called a closure in the computer science literature.
看下面的例子:
function makeCounter () { let counter = 0; return function() {return counter++;}; } let counter = makeCounter(); console.log(counter()); console.log(counter()); console.log(counter()); #+RESULTS: : 0 : 1 : 2
對這個(gè)嵌套函數而言,最有意思的一點(diǎn)是:當外部函數被調用返回后(這里是makeCounter()), 再也沒(méi)有任何手段能夠觸及到 counter 這個(gè)變量。只有內嵌函數擁有專(zhuān)屬權限抵達該變量。
二、Closure的標準定義
開(kāi)發(fā)者通常應該都知道“閉包”這個(gè)通用的編程術(shù)語(yǔ)。
閉包 是指內部函數總是可以訪(fǎng)問(wèn)其所在的外部函數中聲明的變量和參數,即使在其外部函數被返回(壽命終結)了之后。在某些編程語(yǔ)言中,這是不可能的,或者應該以特殊的方式編寫(xiě)函數來(lái)實(shí)現。但是如上所述,在 JavaScript 中,所有函數都是天生閉包的(只有一個(gè)例外,將在 "new Function" 語(yǔ)法 中講到)。
也就是說(shuō):JavaScript 中的函數會(huì )自動(dòng)通過(guò)隱藏的 [[Environment]] 屬性記住創(chuàng )建它們的位置,所以它們都可以訪(fǎng)問(wèn)外部變量。
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站