var、let、const三種聲明變量方式之間的差別

var、let、const三種聲明變量方式之間的差別
  • var聲明的變量會掛載到window上,而let和const聲明的變量不會
var a = 'foo'
console.log(window.a) // foo

let b = 'bar'
console.log(window.b) // undefined

const c = 'baz'
console.log(window.c) // undefined複製代碼
  • var 存在變量提高,而let和const不存在變量提高,let和const上面的區域稱爲「暫時性死區」,在定義以前不能夠使用
console.log(a) // undefined
var a = 'foo'

console.log(b) // test4.html:14 Uncaught ReferenceError: Cannot access 'b' before initialization
let b = 'bar'

console.log(c) // test4.html:14 Uncaught ReferenceError: Cannot access 'c' before initialization
const c = 'baz'複製代碼
  • let和const的聲明會造成塊級做用域
if (true) {
    var a = 'foo'
    let b = 'bar'
}
console.log(a) // foo
console.log(b) // Uncaught ReferenceError: b is not defined

if (true) {
    var a = 'foo'
    const c = 'baz'
}
console.log(a) // foo
console.log(c) // Uncaught ReferenceError: c is not defined複製代碼
  • 在同一個做用域下,let和const不能再次聲明同一個變量,而var能夠
var a = 'foo'
var a = 'bar'
console.log(a) // bar

let b = 'foo'
let b = 'bar'
console.log(b) // test4.html:34 Uncaught SyntaxError: Identifier 'b' has already been declared

const c = 'foo'
const c = 'bar'
console.log(c) // Uncaught SyntaxError: Identifier 'c' has already been declared複製代碼
  • let定義變量以後能夠修改,而const表面上像是聲明一個「常量」。const並非保證變量的值不得改動,而是指變量指向的內存地址不得改變。對於簡單數據類型(Number、String、Boolean),值就保存在變量指向的內存地址,所以等同於常量;而對於複合數據類型(主要是對象和數組),變量只是保存了指向堆內存的地址,至於堆內的數據是否是可變的,就不能控制了。
const person = {}
person.name = 'maoxiaoxing'
console.log(person) // {name: "maoxiaoxing"}

person = {name: 'king'} // test4.html:45 Uncaught TypeError: Assignment to constant variable.

const a = ['foo']
a.push('bar')
a[2] = 'baz'
console.log(a) // ["foo", "bar", "baz"]複製代碼
相關文章
相關標籤/搜索