国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

JavaScript中什么是閉包

發(fā)布時(shí)間:2021-07-03 23:03 來(lái)源:億速云 閱讀:0 作者:Leah 欄目: 開(kāi)發(fā)技術(shù)

這篇文章給大家介紹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í),將立刻刪除涉嫌侵權內容。

日韩69永久免费视频| 色综合视频一区中文字幕| 久久久久久国产精品MV| 色综合久久网| 日韩AV无码一区二区三区无码| 国产在线观看免费视频在线|