JS-閉包(Closures)和let宣告塊級作用域變數
阿新 • • 發佈:2019-01-03
閉包:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures
閉包是函式和宣告該函式的詞法環境的組合。
let:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/let
let 語句宣告一個塊級作用域的本地變數,並且可選的將其初始化為一個值。
例:閉包和let修正匿名函式訪問的變數
function foo(){ var bar = []; for (var index = 0; index < 9; index++) { bar[index] = function(){ return index; } } return bar; } function foo_closures(){ var bar = []; for (let index = 0; index < 9; index++) { (bar[index] = function(){ return index; })() } return bar; } function foo_let(){ var bar = []; for (let index = 0; index < 9; index++) { bar[index] = function(){ return index; } } return bar; } for(var d of foo()){ console.log(d());// 9個9 } for(var d of foo_closures()){ console.log(d());// 1,2,...8 } for(var d of foo_let()){ console.log(d());// 1,2,...8 }