發布自Kindem的博客,歡迎大家轉載,但是要注意注明出處。另外,該文章收納在Kindem的個人的 IT 知識整理倉庫,歡迎 Star、Fork、投稿
let
let
是在ES6
加入的新的變量聲明方法,let
聲明變量的方法和var
類似:
let a = 'hello';
var b = 'hello';
復制代碼
let
的功能是聲明一個作用域被限制在塊級的變量,而var
聲明的變量的作用域只能是全局的或者整個函數塊的
function varTest() {var x = 1;if (true) {var x = 2;// 2console.log(x);}// 2console.log(x);
}function letTest() {let x = 1;if (true) {let x = 2;// 2console.log(x);}// 1console.log(x);
}
復制代碼
再舉一個例子:
var a = 1;
var b = 2;if (a === 1) {var a = 11;let b = 22;// 11console.log(a);// 22console.log(b);
}// 11
console.log(a);
// 2
console.log(b);
復制代碼
另外,如果作用域位于程序的頂層,var
會掛載到window
上,而let
不會:
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;// SyntaxErrorlet foo;
}
復制代碼
let
和var
都會在聲明所在的作用域頂部被創建,這被稱為變量提升
,但是不同的是var
的創建會伴隨著一個undefined
值,在賦值之后才會改變,而let
沒有被賦值之前是不會被初始化的,如果在這期間引用let
聲明的變量,會導致一個ReferenceError
,直到初始化之前,該變量都處于暫存死區
:
function test() {// undefinedconsole.log(bar);// ReferenceErrorconsole.log(foo);var bar = 1;let foo = 2;
}
test();
復制代碼
兩個復雜一點的例子:
function test(){var foo = 33;if (true) {// ReferenceErrorlet foo = (foo + 55);}
}
test();
復制代碼
function go(n) {// Object {a: [1,2,3]}console.log(n);// ReferenceErrorfor (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 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';// aconsole.log(a);// bconsole.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);
復制代碼