js閉包學習心得總結
首先引用來自官網(wǎng)文檔的定義:
closure is the combination of a function and the lexical environment within which that function was declared.
閉包是一個函數(shù)和其內部公開變量的環(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()內部的閉包函數(shù),而為啥在displayName內部可以調用到外部定義的變量 name 呢,因為js內部函數(shù)有獲取外部函數(shù)中變量的權限。
第二個例子
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í)行結束了,i是固定值,并沒有實現(xiàn)我們期望的效果。
console.log(this); 發(fā)現(xiàn) this 指向的是 Window,也就是說,在函數(shù)內部實現(xiàn)的閉包函數(shù)已經(jīng)被轉變成了全局函數(shù),存儲到了內存中。
所以需要再定義一個執(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(); // 得到預期的 10 11 12
相關文章
JavaScript 異步調用框架 (Part 4 - 鏈式調用)
我們已經(jīng)實現(xiàn)了一個簡單的異步調用框架,然而還有一些美中不足,那就是順序執(zhí)行的異步函數(shù)需要用嵌套的方式來聲明。2009-08-08