Are variables declared with let or const not hoisted in ES6?
我在ES6上玩了一段时间,我注意到,虽然用
1 2 | console.log(typeof name); // undefined var name ="John"; |
…用
1 2 | console.log(typeof name); // ReferenceError let name ="John"; |
和
1 2 | console.log(typeof name); // ReferenceError const name ="John"; |
这是否意味着用
@当然,在声明这些变量之前,它们不能被访问是正确的。不过,这比这要复杂一些。
Are variables declared with
let orconst not hoisted? What is really going on here?
所有声明(
1 2 3 4 5 6 7 8 9 10 11 12 13 | x ="global"; // function scope: (function() { x; // not"global" var/let/… x; }()); // block scope (not for `var`s): { x; // not"global" let/const/… x; } |
这对于函数和块作用域1都是正确的。
1 2 3 4 5 6 7 8 | x = y ="global"; (function() { x; // undefined y; // Reference error: y is not defined var x ="local"; let y ="local"; }()); |
注意,
时间死区不是句法位置,而是变量(作用域)创建和初始化之间的时间。只要代码没有被执行(例如,函数体或简单的死代码),引用声明上面代码中的变量不是一个错误,并且如果在初始化之前访问变量,即使访问代码低于声明(例如,在也被调用的提升函数声明中),它也会抛出异常早期)。
Is there any difference between
let andconst in this matter?
不,就起重而言,它们的工作原理是一样的。它们之间的唯一区别是,一个
1:EDOCX1[4]声明仍然只在功能级别工作,当然
引用ecmascript 6(ecmascript 2015)规范,
The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated.
因此,要回答您的问题,是的,
基本上,
- 当你用
var 关键字定义一个变量时,它从定义的那一刻起就知道整个函数。 当使用
let 语句定义变量时,它只在定义的块中知道。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29function doSomething(arr){
//i is known here but undefined
//j is not known here
console.log(i);
console.log(j);
for(var i=0; i<arr.length; i++){
//i is known here
}
//i is known here
//j is not known here
console.log(i);
console.log(j);
for(let j=0; j<arr.length; j++){
//j is known here
}
//i is known here
//j is not known here
console.log(i);
console.log(j);
}
doSomething(["Thalaivar","Vinoth","Kabali","Dinesh"]);
如果运行代码,可以看到变量
使用let还有另一个巨大的优势,因为它创建了一个新的词汇环境,并且还绑定了新的值,而不是保留旧的引用。
1 2 3 4 5 6 7 8 9 10 11 | for(var i=1; i<6; i++){ setTimeout(function(){ console.log(i); },1000) } for(let i=1; i<6; i++){ setTimeout(function(){ console.log(i); },1000) } |
第一个
对于
1 2 3 4 5 6 7 8 9 10 11 12 | const foo = {}; foo.bar = 42; console.log(foo.bar); //works const name = [] name.push("Vinoth"); console.log(name); //works const age = 100; age = 20; //Throws Uncaught TypeError: Assignment to constant variable. console.log(age); |
如果常数指的是