004.ES2015和ES2016新特性--块级做用域变量

其基本原理就是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
相关文章
相关标签/搜索