setTimeout中let和var的区别? [英] Difference between let and var inside setTimeout?

查看:646
本文介绍了setTimeout中let和var的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道let和var之间的区别。 let是块范围,var是功能范围。

I know the difference between let and var. let is block scope and var is functional scope.

for(var i=0; i< 3; i++){
    setTimeout(function(){
        console.log(i);
    }, 10);
}

output : 3
         3
         3

我知道上面的代码片段是如何工作的( console.log(i)当i的值为3时正在执行,因为i的范围是全球)。

I know how above code snippet is working(console.log(i) is executing at that time when value of i is 3, because scope of i is global).

但是

for(let i=0; i< 3; i++){
    setTimeout(function(){
        console.log(i);
    }, 10);
}

output : 1
         2
         3

以上代码段令我困惑。据我说它应该抛出引用错误(因为 console.log(i)执行的时间,将在全局范围内查看i的值而不是在本地范围内,并且我不是在全局声明/定义。所以它应该给出引用错误。)

the above code snippet confusing me. according to me it should throw Reference Error(because the time when console.log(i) execute, will look the value of i in global scope not in local scope, and i is not declare/defined in global. so it should give reference error.)

任何能解释第二个循环如何在运行时工作的人?

Anyone who can explain how 2nd for loop working on Runtime ?

推荐答案

这是关闭的魔力。在你的循环中

This is the magic of closure. In side your loop

for(let i=0; i< 3; i++){
    setTimeout(function(){
        console.log(i);
    }, 10);
}

你宣布一项功能

function(){
  console.log(i);
}

此外,循环本身声明阻止

for(let i=0; i< 3; i++){
  // this is a block scope because it is contained in 
  // braces
}

使用 let 定义的变量是块作用域。

Variables defined with let are block scoped.

由于闭包,您在循环中声明的函数可以访问其范围及其父范围中声明的所有变量,直到它被垃圾回收。

Because of closure, the function you declare inside the loop has access to all the variables declared in its scope and its parents scopes until it is garbage collected.


闭包是函数与声明该函数的词汇环境
的组合。这个环境包含
在创建闭包
时在范围内的任何局部变量。

A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time that the closure was created.

当创建 setTimeout 使用的函数时,变量 i 范围内 。对于循环的每次迭代,引用的 i i 的不同实例。

The variable i is in-scope when the functions used by setTimeout are created. The i referred to is a different instance of i for each iteration of the loop.

该函数一直存在,直到您声明的间隔通过。这就是为什么在你的循环中声明的3个函数中的每一个都打印 i的值; 它在包含范围内声明,并且仍然可用于

The function exists until the interval you declared passes. That is why each of the 3 functions declared in your loop print the value of i; it was declared in the containing scope and remains available to the function.

这篇关于setTimeout中let和var的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆