iT邦幫忙

0

Hoisting

關於Hoisting很像是變數被拉升到上層

  • 提升變數不會賦值
  • var a = 2 LHS
  • console.log(a) RHS

尚未宣告變數,即RHS該數值便會出現參考錯誤

console.log(a) //ReferenceError: a is not defined

這邊Hoisting

console.log(a) //undefined
var a = 1;
var a;

Var

在學習了Let之後,盡量少用Var。原因是Var會被提升到全域變數並且被汙染,並且可以重複被宣告改賦值,造成程式錯誤

a = 1;
var a;

console.log(a) //1

compiler 會把程式看成兩個敘述句

var a
a = 2

Let

不能重複宣告

let u = 0
let u = 1
console.log(u) //SyntaxError: Identifier 'u' has already been declared


var a = 10

function test(){
    console.log(a)
    let a //ReferenceError: Cannot access 'a' before initialization
}
test()

Const

Const可以看作Let的加強版,並且Const不能改變賦值

var a = 10

function test(){
    console.log(a)
    const a //ReferenceError: Cannot access 'a' before initialization
}
test()

尚未有邦友留言

立即登入留言