js閉包及var和let對閉包的作用
爲了便於理解,本文用一個例子程序來體現js閉包和var、let變量聲明對所謂閉包的作用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
function test() {
for(var i=0;i<10;i++){
console.log(i);
}
};
var testclosing_innerfuncs=[];
function test_closing(){
for(var inner=0;inner<10;inner++){
testclosing_innerfuncs.push(function f() {
console.log(inner);
})
}
}
var testavoidclosing_innerfuncs=[];
function test_avoidclosing(){
for(let inner=0;inner<10;inner++){
testavoidclosing_innerfuncs.push(function f() {
console.log(inner);
})
}
}
test();
console.log("------------");
test_closing();
testclosing_innerfuncs.forEach(item=>{
item();
});
console.log("------------");
test_avoidclosing();
testavoidclosing_innerfuncs.forEach(item=>{
item();
})
</script>
<body>
</body>
</html>
以上例子控制檯輸出:
其中第一個函數test()是普通函數,用於對比。
第二個函數test_closing是存在閉包的函數,雖然函數內部變量inner作用域只存在函數內循環體,但由於全局變量testclosing_innerfuncs的賦值引用,所以在執行test_closing函數時,仍然可以使用該內部變量,但由於閉包,調用時inner早已循環遞加到10,所以輸出10個10。
第三個函數test_avoidclosing是避免閉包對原始函數的影響,方法是讓內部變量inner用let聲明而不是var,let使變量只在作用域內有效,而不會存在於閉包所在的“氣泡”(引自Secrets of the JavaScript Ninja)中。