ES6引入Let随block level scoping. 直到ES5我们没有block level scoping,所以在块内声明的变量始终hoisted是函数级别的范围。
基本上Scope是指您的变量在程序中的可见位置,这决定了您可以在何处使用已声明的变量。在ES5我们有global scope,function scope and try/catch scope, withES6我们还通过使用 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只在 the 中loop而不是 before 和 after 中是已知的。然而,我们的变量从定义的那一刻起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循环总是打印最后一个值,let它创建一个新的范围并绑定打印 us 的新值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);
如果常量引用 an object,它将始终引用 theobject但它object本身可以更改(如果它是可变的)。如果你喜欢不可变的object,你可以使用Object.freeze([])