我想了解javascript引擎如何以及何时将值传递给回调函数,我尝试过调试和在线查找,但无法找到确切的答案,请考虑以下示例:
for(var i = 0; i < 4; i++) {
    console.log("outside callback " + i + " ");
    setTimeout(function test(){
      console.log("inside callback " + i + " ");
    },100);
}此输出跟随输出。
外部回调0 外部回调1 外部回调2 外部回调3 内部回调4 内部回调4 内部回调4 内部回调4
如果我只是使用let关键字更改i变量的声明,如下所示:
for(let i = 0; i < 4; i++) {
    console.log("outside callback " + i + " ");
    
    setTimeout(function test(){
       console.log("inside callback " + i + " ");
    },100);
}其结果如下:
外部回调0 外部回调1 外部回调2 外部回调3 内部回调0 内部回调1 内部回调2 内部回调3
在Chrome中调试时,它在第一个示例中显示I作为测试函数的闭包作用域,在第二个示例中显示块范围。
发布于 2017-07-10 13:43:38
这与有关内部循环JavaScript闭包-简单实用示例的一个常见问题有关,该问题详细说明了为什么在循环中创建内部回调函数时,使用var声明的变量具有在循环结束时达到的值:虽然在设置回调时它们可能持有不同的值,但在执行回调时,异步地在一段时间后,循环已经完成,并且在闭包中保留了循环完成时保存的值。
从ECMAScript版本6开始,使用let声明的变量是块作用域,不能在定义它们的代码块之外访问它们。此外,在for循环控制语句中定义的变量将得到特殊处理。
for循环体,而不是包含for循环的代码块。let变量绑定。这意味着每个迭代都可以有自己的一组变量值,保存在为迭代创建的词法环境记录中,这些值可以在闭包中使用,并由循环中定义的回调函数访问。- In the first iteration, `let` defined variables within the `for` statement have the values they would have after executing `part1` and `part2`.
- In subsequent iterations, they have the values determined by initializing their values in the environment record for the current iteration with those they had at the end of the previous iteration, and then executing `part3` and `part2` in the `for` statement above.
- call back functions declared inside the `for` loop body access the value of `let` defined variables held at the _end_ of the iteration in which the call back was set up, _excluding_ side effects of evaluating `part3` of the `for` statement.
发布于 2017-07-10 12:29:03
这实际上是因为使用let和var声明的瓦莱布范围,而不仅仅是javascript的闭包属性。
https://stackoverflow.com/questions/45011895
复制相似问题