js閉包學(xué)習(xí)心得總結(jié)
首先引用來自官網(wǎng)文檔的定義:
closure is the combination of a function and the lexical environment within which that function was declared.
閉包是一個函數(shù)和其內(nèi)部公開變量的環(huán)境的集合.
簡單而言, 閉包 = 函數(shù) + 環(huán)境
第一個閉包的例子
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().
其實這個栗子很簡單,displayName()就是init()內(nèi)部的閉包函數(shù),而為啥在displayName內(nèi)部可以調(diào)用到外部定義的變量 name 呢,因為js內(nèi)部函數(shù)有獲取外部函數(shù)中變量的權(quán)限。
第二個例子
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();
上面這個例子可以正確輸出 10 11 12 嗎?
答案是:并不能,并且還會報語法錯誤....
console.log(i); 發(fā)現(xiàn)i輸出了3次3,也就是說,在setTimeout 1000毫秒之后,執(zhí)行閉包函數(shù)的時候,for循環(huán)已經(jīng)執(zhí)行結(jié)束了,i是固定值,并沒有實現(xiàn)我們期望的效果。
console.log(this); 發(fā)現(xiàn) this 指向的是 Window,也就是說,在函數(shù)內(nèi)部實現(xiàn)的閉包函數(shù)已經(jīng)被轉(zhuǎn)變成了全局函數(shù),存儲到了內(nèi)存中。
所以需要再定義一個執(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)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12
JavaScript 異步調(diào)用框架 (Part 4 - 鏈式調(diào)用)
我們已經(jīng)實現(xiàn)了一個簡單的異步調(diào)用框架,然而還有一些美中不足,那就是順序執(zhí)行的異步函數(shù)需要用嵌套的方式來聲明。2009-08-08

