宣告會提升但賦值不會


test()

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

在 function 裡的 a 提升

宣告變數會提升,賦值不會

var a = 'global'

function test() {
  console.log(a)
  var a = '10'
}

test()
// a is undelined

function 的優先度高於宣告變數

function test() {
  console.log(a)
  function a() {}
  var a = 'local'
}

test() // f a() {}

同時宣告兩個一樣的 function,後者勝

var a = 'global'

function test() {
  a()
  function a() {
    console.log(1)
  }
  function a() {
    console.log(2)
  }
  var a = 'local'
}

test() // 2

hoisting 提升的順序

  1. function
  2. arguments (參數)
  3. var

參考資源


#程式導師實驗計畫第四期 #前端 #hoisting







Related Posts

[Linux] windows遠端 + wsl + docker 開放 0.0.0.0:8080 給外部使用

[Linux] windows遠端 + wsl + docker 開放 0.0.0.0:8080 給外部使用

Week1 筆記| [CMD101] Command Line 學習筆記

Week1 筆記| [CMD101] Command Line 學習筆記

Golang - 條件式與迴圈

Golang - 條件式與迴圈


Comments