发布自 Kindem的博客,欢迎你们转载,可是要注意注明出处。另外,该文章收纳在 Kindem的我的的 IT 知识整理仓库,欢迎 Star、Fork、投稿
let
是在ES6
加入的新的变量声明方法,let
声明变量的方法和var
相似:javascript
let a = 'hello'; var b = 'hello';
let
的功能是声明一个做用域被限制在块级的变量,而var
声明的变量的做用域只能是全局的或者整个函数块的java
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); }
再举一个例子:git
var a = 1; var b = 2; if (a === 1) { var a = 11; let b = 22; // 11 console.log(a); // 22 console.log(b); } // 11 console.log(a); // 2 console.log(b);
另外,若是做用域位于程序的顶层,var
会挂载到window
上,而let
不会:github
var a = 'a'; let b = 'b'; // this -> window // a console.log(this.a); // undefined console.log(this.b); // a console.log(window.a); // undefined console.log(window.b);
在相同的函数或块做用域内从新声明同一个变量会引起一个重复定义的SyntaxError
函数
if (x) { let foo; // SyntaxError let foo; }
let
和var
都会在声明所在的做用域顶部被建立,这被称为变量提高
,可是不一样的是var
的建立会伴随着一个undefined
值,在赋值以后才会改变,而let
没有被赋值以前是不会被初始化的,若是在这期间引用let
声明的变量,会致使一个ReferenceError
,直到初始化以前,该变量都处于暂存死区
:this
function test() { // undefined console.log(bar); // ReferenceError console.log(foo); var bar = 1; let foo = 2; } test();
两个复杂一点的例子:code
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
的基本做用是声明一个做用域被限制在块级的常量,其做用域和let
同样,基本使用也和let
相似,可是const
的特色是const
声明的值一经建立没法被改变对象
使用const
会建立一个值的只读引用,这意味着const
声明的对象本省的引用是没法被改变的,可是其属性是能够被改变的,由于改变其属性并不会引发其引用的变化ip
下面给出const
的一些特性的例子:作用域
基本使用:
const a = 'abc';
没法被重复定义:
const a = 'abc'; // SyntaxError: Identifier 'a' has already been declared const a = 'abc';
声明时就必须赋值:
// SyntaxError: Missing initializer in const declaration const a;
没法被修改:
const a = 'a'; // TypeError: Assignment to constant variable a = 'b';
块级做用域:
if (true) { var a = 'a'; const b = 'b'; // a console.log(a); // b console.log(b); } // a console.log(a); // ReferenceError: not defined console.log(b);
做用域在程序顶层时不会挂在window
对象上:
var a = 'a'; const b = 'b'; // this -> window // a console.log(this.a); // undefined console.log(this.b); // a console.log(window.a); // undefined console.log(window.b);