ES6 的 let 和 const 都是新引入的关键字。它们不会被提升,而且是块作用域。也就是说被大括号包围起来的区域声明的变量外部将不可访问。
let 声明
过早访问 let 声明的引用导致的这个 referenceerror 叫做临时死亡区错误.你在访问一个已经声明但还没有初始化的变量. 创建一个块作用域.
let g1 ='global 1'let g2 ='global 2'{ /* Creating a new block scope */ g1 ='new global 1'let g2 ='local global 2'console.log(g1) // 'new global 1'console.log(g2) // 'local global 2'console.log(g3) // ReferenceError: g3 is not definedlet g3 ='I am not hoisted';}console.log(g1) // 'new global 1'console.log(g2) // 'global 2'
consttryMe='initial assignment'; tryMe ='this has been reassigned'; // TypeError: Assignment to constant variable.// You cannot reassign but you can change it…constarray= ['Ted','is','awesome!']; array[0] ='Barney'; array[3] ='Suit up!';console.log(array); // [“Barney”, “is”, “awesome!”, “Suit up!”]constairplane= {};airplane.wings =2;airplane.passengers =200;console.log(airplane); // {passengers: 200, wings: 2}
常见例子
functionouter() {let a =1;functioninner() {let b =2;functioninnermost() {let c =3;console.log(a, b, c); // 1 2 3 }innermost();console.log(a, b); // 1 2 — 'c' is not defined }inner();console.log(a); // 1 — 'b' and 'c' are not defined}
{ /* Original code */console.log(i); // undefinedvar i =10console.log(i); // 10}{ /* Compilation phase */var i;console.log(i); // undefined i =10console.log(i); // 10}// ES6 let & const{console.log(i); // ReferenceError: i is not definedconsti=10console.log(i); // 10}{console.log(i); // ReferenceError: i is not definedlet i =10console.log(i); // 10}
functiongreeting() {console.log(s) // undefinedif(true) {var s ='Hi'; undeclaredVar ='I am automatically created in global scope'; }console.log(s) // 'Hi'}console.log(s); // Error — ReferenceError: s is not definedgreeting();console.log(undeclaredVar) // 'I am automatically created in global scope'
let a =2;if(a>1){let b = a +1;console.log(b) //6for(let i = a; i <=b;i ++){let j = i +10;console.log(j) }//12 13 14 15 16let c = a+ b;console.log('c: ', c);}
总结
默认使用 const, 只在确实需要改变的时候使用 let, 这样就可以在某种程度上实现代码的不可变。从而防止某些错误的产生。