我试图了解JS中作用域是如何工作的。如果我理解了这段代码,你能告诉我吗:
for(var i = 0; i<5; i++){
setTimeout(function timeoutHandler() {
var i = i;
console.log(i); //undefined
})
}console.log打印undefined 5次。因此,正如我所理解的,在执行timeoutHandler时,它有自己的本地作用域和自己的i变量。那么,在timeoutHandler执行期间,解释器请求i变量,发现它在本地范围中声明并使用这个声明的变量进行赋值,这是正确的吗?这解释了为什么它是undefined,但我不确定我是否完全正确。谢谢
UPD我不需要这些代码才能正常工作,我只想了解为什么在这种情况下它的行为是这样的
发布于 2017-10-20 11:12:58
试图通过这个例子来理解它:
for(var i = 0; i<5; i++){
//create a self executing function
(function(iValue){
//in this scope iValue has the i from the loop
setTimeout(function() {
console.log(iValue); //will print the correct i
})
})(i); //pass i in it's current context to the function
}
或者使用ES6更容易:使用let而不是var。因为let是在块中限定作用域的(循环的每次运行都是自己的块),所以它不会在setTimeout中获得另一个值。
for(let i = 0; i<5; i++){
setTimeout(function() {
console.log(i); //will print the correct i
})
}
https://stackoverflow.com/questions/46847423
复制相似问题