宣告會提升但賦值不會


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

[Vue 學習筆記(二)] Vue class 和 style binding

[Vue 學習筆記(二)] Vue class 和 style binding

T1.1_Sass 裝好了,可是 - -watch 不能用?

T1.1_Sass 裝好了,可是 - -watch 不能用?

content-length mismatch composer laravel

content-length mismatch composer laravel


Comments