let 和循环闭包

前端之家收集整理的这篇文章主要介绍了let 和循环闭包前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这个是臭名昭著的循环加闭包。匿名函数调用的时候,会在作用域链上找i,最后它会在外层函数的作用域里面找到这个变量,而这个变量的值就是10,所有的匿名函数都会返回10。

针对这段代码,通常有两个解决方案:

这个办法就是每次定义匿名函数的时候都把相应的i截取下来,而不需要在调用的时候去作用域链找这个值。

还有一个用let的:

经常很多地方会说,用这个办法能解决是因为 let 能创建块级作用域,但是我从来没理解为什么块级作用域和这有什么关系,直到今天看 NCZ 的

This loop works exactly like the loop that used var and an IIFE but is,arguably,cleaner. 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. The same is true for for-in and for-of loops.

It’s important to understand that the behavior of let declarations in loops is a specially-defined behavior in the specification and is not necessarily related to the non-hoisting characteristics of let. In fact,early implementations of let did not have this behavior,as it was added later on in the process.

如果 let 做的仅仅是创建一个块级作用域的话,循环里面的匿名函数还是要在作用域链上去找i,区别只不过是之前的i是在外层函数的变量对象里找到的,而现在是在循环块的变量对象里找到的,而已。重要的是,let 使得每次循环都给了匿名函数一个i的值,它不必在调用的时候再去作用域链上找了。

猜你在找的程序笔记相关文章