JS 閉包

來源:互聯網
上載者:User

標籤:使用   os   問題   cti   for   io   

一個你可能覺得很奇怪的現象
var batch = [];
var i = 0;
for(;i < 5; i++){
batch.push(function closureFn(){
console.log(i);
});
}

batch.forEach(function(item){item();console.log("<"+i+">")});
輸出
5
<5>
5
<5>
5
<5>
5
<5>
5
<5>
輸出的值都是i最後的結果

這個函數做的事情是向push數組中存放元素 這個元素是函數 且函數沒有執行
所以輸出一下batch得到
[function closureFn(){
console.log(i);
}, function closureFn(){
console.log(i);
}, function closureFn(){
console.log(i);
}, function closureFn(){
console.log(i);
}, function closureFn(){
console.log(i);
}]

對batch的每一項進行遍曆
forEach中的item就是
function closureFn(){
console.log(i);
}這個函數
故item() 啟動並執行話就是輸出最終的i值

PS batch這個數組中的forEach的回呼函數中變數i是全域變數i

 

或者用這個例子
var batch = [];
var i = 0;
for(;i < 5; i++){
batch.push(function closureFn(){
return i;
});
}
batch.forEach(function(f){console.log(f())});
得到5個5
這也是同樣的道理

 

//使用立即執行函數來解決這個問題
var batch = [];
var i = 0;
for(;i < 5; i++){
batch.push(function closureFn(i){
console.log(i+" .. ");
return i;
}(i));
}
console.log(batch); //[0, 1, 2, 3, 4]

或者這樣 加深印象
var batch = [];
var i = 0;
for(;i < 5; i++){
batch.push(function closureFn(index){
return function(){ console.log(i+" "+index)};
}(i));
}
batch.forEach(function(item){item()});

輸出結果
5 0
5 1
5 2
5 3
5 4

這裡使用了立即執行函數 所以每一次迴圈參數index得到的都是該輪迴圈的index
PS index不是i的引用 而是每次迴圈的時候i將自己的值傳給index
closureFn這個函數立即執行 並且返回一個函數 這個返回的函數就是batch中的一個元素


PS 閉包中儲存的是外部變數的引用而非值
所以for迴圈執行完後 i的值就已經是5 forEach每一項 在執行返回函數的時候i就是5

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.