js閉包學(xué)習(xí)心得總結(jié)
首先引用來(lái)自官網(wǎng)文檔的定義:
closure is the combination of a function and the lexical environment within which that function was declared.
閉包是一個(gè)函數(shù)和其內(nèi)部公開(kāi)變量的環(huán)境的集合.
簡(jiǎn)單而言, 閉包 = 函數(shù) + 環(huán)境
第一個(gè)閉包的例子
function init() { var name = 'Mozilla'; // name is a local variable created by init function displayName() { // displayName() is the inner function, a closure alert(name); // use variable declared in the parent function } displayName(); } init(); because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().
其實(shí)這個(gè)栗子很簡(jiǎn)單,displayName()就是init()內(nèi)部的閉包函數(shù),而為啥在displayName內(nèi)部可以調(diào)用到外部定義的變量 name 呢,因?yàn)閖s內(nèi)部函數(shù)有獲取外部函數(shù)中變量的權(quán)限。
第二個(gè)例子
var data = [ {'key':0}, {'key':1}, {'key':2} ]; function showKey() { for(var i=0;i<data.length;i++) { setTimeout(function(){ //console.log(i); //發(fā)現(xiàn)i輸出了3次3 //console.log(this); // 發(fā)現(xiàn) this 指向的是 Window data[i].key = data[i].key + 10; console.log(data[i].key) }, 1000); } } showKey();
上面這個(gè)例子可以正確輸出 10 11 12 嗎?
答案是:并不能,并且還會(huì)報(bào)語(yǔ)法錯(cuò)誤....
console.log(i); 發(fā)現(xiàn)i輸出了3次3,也就是說(shuō),在setTimeout 1000毫秒之后,執(zhí)行閉包函數(shù)的時(shí)候,for循環(huán)已經(jīng)執(zhí)行結(jié)束了,i是固定值,并沒(méi)有實(shí)現(xiàn)我們期望的效果。
console.log(this); 發(fā)現(xiàn) this 指向的是 Window,也就是說(shuō),在函數(shù)內(nèi)部實(shí)現(xiàn)的閉包函數(shù)已經(jīng)被轉(zhuǎn)變成了全局函數(shù),存儲(chǔ)到了內(nèi)存中。
所以需要再定義一個(gè)執(zhí)行函數(shù)
var data = [ {'key':0}, {'key':1}, {'key':2} ]; function showKey() { var f1 = function(n){ data[i].key = data[i].key + 10; console.log(data[i].key) } for(var i=0;i<data.length;i++) { setTimeout(f1(i), 1000); } } showKey(); // 得到預(yù)期的 10 11 12
相關(guān)文章
Bootstrap整體框架之JavaScript插件架構(gòu)
這篇文章主要介紹了Bootstrap整體框架之JavaScript插件架構(gòu)的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12JavaScript 異步調(diào)用框架 (Part 4 - 鏈?zhǔn)秸{(diào)用)
我們已經(jīng)實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的異步調(diào)用框架,然而還有一些美中不足,那就是順序執(zhí)行的異步函數(shù)需要用嵌套的方式來(lái)聲明。2009-08-08cloneNode實(shí)現(xiàn)表格增加刪除效果
cloneNode實(shí)現(xiàn)表格增加刪除效果...2006-11-11微信小程序的tab選項(xiàng)卡的實(shí)現(xiàn)效果
這篇文章主要介紹了微信小程序的tab選項(xiàng)卡的實(shí)現(xiàn)效果,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05