ES6 引入了Let 变量,这些变量与block level scoping 一起出现。在ES5 之前,我们没有block level scoping,因此在块内声明的变量始终是hoisted 函数级别范围。
基本上Scope 是指您的变量在程序中的可见位置,这决定了您可以在何处使用已声明的变量。在ES5 中,我们有global scope,function scope and try/catch scope,在ES6 中,我们还可以使用Let 获得块级范围。
- 当您使用
var 关键字定义变量时,它从定义的那一刻起就知道整个函数。
-
当您使用let 语句定义变量时,它仅在它定义的块中知道。
function 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"]);
如果您运行代码,您会看到变量j 仅在loop 中已知,而不是之前和之后。然而,我们的变量 i 从定义的那一刻起就在 entire function 中已知。
使用 let 还有一个很大的优势,因为它创建了一个新的词法环境,并且还绑定了新的值而不是保留旧的引用。
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)
}
第一个 for 循环总是打印 last 值,let 它创建一个新范围并绑定新值,打印我们 1, 2, 3, 4, 5。
来到constants,它基本上和let一样工作,唯一的区别是它们的值不能改变。在常量中允许改变,但不允许重新分配。
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);
如果常量引用object,它将始终引用object,但object 本身可以更改(如果它是可变的)。如果你想要一个不可变的object,你可以使用Object.freeze([])