先附上nzakas的讲解地址:
https://github.com/nzakas/understandinges6/blob/master/manuscript/01-Block-Bindings.md
在zakas对let的讲解中举的例子:
var funcs = []; for (let i = 0; i < 10; i++) { funcs.push(function() { console.log(i); }); } funcs.forEach(function(func) { func(); // outputs 0, then 1, then 2, up to 9 })
其解释为
1.On each iteration, the loop creates a new variable and initializes it to the value of the variable with the same name from the previous iteration.
2.The let declaration creates a new variable i each time through the loop, so each function created inside the loop gets its own copy of i. Each copy of i has the value it was assigned at the beginning of the loop iteration in which it was created
这意味着每次迭代,都会重新用let声明i,赋值,并且产生一个新的块级域,我这样理解对不对呢?是否等价于{let i = 0;...}{let i = 1;...}...{let i = 9;...}分为10个块级域,而且每个i都处在不同块级域之中呢? 但是同为块级域的const:
var funcs = []; // throws an error after one iteration for (const i = 0; i < 10; i++) { funcs.push(function() { console.log(i); }); }
为什么不会在每次迭代中重新声明赋值并且产生新的块级域呢?像{const i = 0;...}{const i = 1;...}...{const i = 9;...}这样呢?这是否说明const和let在for迭代中的行为不同呢? 然而,在for-in和for-of循环之中,为什么let与const又是相同的?
var funcs = [], object = { a: true, b: true, c: true }; // doesn't cause an error for (const key in object) { funcs.push(function() { console.log(key); }); } funcs.forEach(function(func) { func(); // outputs "a", then "b", then "c" });
其解释为The for-in and for-of loops work with const because the loop initializer creates a new binding on each iteration through the loop rather than attempting to modify the value of an existing binding 这里有一些不解,每次产生新绑定和在现有绑定上修改之间有什么区别吗?for-in循环不是将属性名赋值给变量吗?为什么是产生绑定了?每迭代一次key的值不都变了吗?为什么仍然能够工作呢? 刚学ES6,对以上实在有些不解,还望大神解答!
for 10 次等于把 i 重新赋值 10 次,const 不允许重新赋值
for..in/of 每次都是声明新变量,不存在重复赋值,所以 const 无碍
求解呀,求解呀