其基本原理就是JavaScript的做用域鏈,下面以對比的方式來展現一下函數級做用域和塊級做用域。javascript
var fns = []; for (var i = 0; i < 5 ; i++){ //fns.push(() => {console.log(i)}); fns.push(function(){ console.log(i) }) } fns.forEach(fn => fn());
運行結果是java
5 5 5 5 5
var fns = []; for (let i = 0; i < 5 ; i++){ //fns.push(() => {console.log(i)}); fns.push(function(){ console.log(i) }) } fns.forEach(fn => fn());
運行結果是shell
0 1 2 3 4