let
的功能是声明一个作用域被限制在块级的变量,而var
声明的变量的作用域只能是全局的或者整个函数块的
function varTest() { var x = 1; if (true) { var x = 2; // 2
console.log(x);
} // 2
console.log(x);
}function letTest() { let x = 1; if (true) { let x = 2; // 2
console.log(x);
} // 1
console.log(x);
}
再举一个例子:
var a = 1;var b = 2;if (a === 1) { var a = 11; let b = 22; // 11
console.log(a); // 22
console.log(b);
}// 11console.log(a);// 2console.log(b);
另外,如果作用域位于程序的顶层,var
会挂载到window
上,而let
不会:
var a = 'a';let b = 'b';// this -> window// aconsole.log(this.a);// undefinedconsole.log(this.b);// aconsole.log(window.a);// undefinedconsole.log(window.b);
在相同的函数或块作用域内重新声明同一个变量会引发一个重复定义的SyntaxError
if (x) { let foo; // SyntaxError
let foo;
}
let
和var
都会在声明所在的作用域顶部被创建,这被称为变量提升
,但是不同的是var
的创建会伴随着一个undefined
值,在赋值之后才会改变,而let
没有被赋值之前是不会被初始化的,如果在这期间引用let
声明的变量,会导致一个ReferenceError
,直到初始化之前,该变量都处于暂存死区
:
function test() { // undefined
console.log(bar); // ReferenceError
console.log(foo); var bar = 1; let foo = 2;
}
test();
两个复杂一点的例子:
function test(){ var foo = 33; if (true) { // ReferenceError
let foo = (foo + 55);
}
}
test();
function go(n) { // Object {a: [1,2,3]}
console.log(n); // ReferenceError
for (let n of n.a) { console.log(n);
}
}
go({a: [1, 2, 3]});
const
const
的基本作用是声明一个作用域被限制在块级的常量,其作用域和let
一样,基本使用也和let
类似,但是const
的特点是const
声明的值一经创建无法被改变
使用const
会创建一个值的只读引用,这意味着const
声明的对象本省的引用是无法被改变的,但是其属性是可以被改变的,因为改变其属性并不会引起其引用的变化
下面给出const
的一些特性的例子:
基本使用:
const a = 'abc';
无法被重复定义:
const a = 'abc';// SyntaxError: Identifier 'a' has already been declaredconst a = 'abc';
声明时就必须赋值:
// SyntaxError: Missing initializer in const declarationconst a;
无法被修改:
const a = 'a';// TypeError: Assignment to constant variablea = 'b';
块级作用域:
if (true) { var a = 'a'; const b = 'b'; // a
console.log(a); // b
console.log(b);
}// aconsole.log(a);// ReferenceError: not definedconsole.log(b);
作用域在程序顶层时不会挂在window
对象上:
var a = 'a';const b = 'b';// this -> window// aconsole.log(this.a);// undefinedconsole.log(this.b);// aconsole.log(window.a);// undefinedconsole.log(window.b);
作者:Kindem
链接:https://www.jianshu.com/p/7c59a6d78b5e