什麼是 scope?


Posted by YongChenSu on 2020-12-09

ES6 以前的 scope

變數的生存範圍

var a = 10
function text() {
  var a =20
  console.log(a) // 20
}
text()
console.log(a) //10


  • function 裡沒有宣告 a 直接變成全域變數
var a = 20
function text() {
  a = 10
  console.log(a) // 10
}
text()
console.log(a) // 10
let a = 'global'
function text() {
  let a = 'testA'
  let b = 'testB'
  console.log(a, b)
  function inner() {
    let b = 'innerB'
    console.log(a, b)  
  }
  inner()
}
text()
console.log(a)

// testA testB
// testA innerB
// global

scope chain

往上找
inner scope -> test scope -> global

let a = 'global'
function text() {
  // let a = 'testA'
  let b = 'testB'
  console.log(a, b)
  function inner() {
    let b = 'innerB'
    console.log(a, b)  
  }
  inner()
}
text()
console.log(a)

// global testB
// global innerB
// global


scope chain 要注意的地方

scope 的判斷跟 function 被呼叫的地方沒有關係,是看放在程式碼的哪裡

scope chain 在宣告的時候就定義好了

p.s. 但 this 會根據呼叫的方式改變值

let a = 'global'
function change() {
  let a = 10
  test()
}
function test() {
  console.log(a) // global
}
change()

ES6 的 scope:let const 的變數生存範圍

var: function scope

function test() {
  var a = 10 
  if (a === 10) {
    var b = 20
  }
  console.log(b)
}
test()
// 20

let、const: block(大括號) scope

function test() {
  let a = 10 
  if (a === 10) {
    let b = 20
  }
  console.log(b)
}
test()
// b is not defined

for 迴圈裡以 var 宣告

function test() {
  for (var i=0; i<10; i++) {
    console.log('i:', i)
  }
  console.log('Final value:', i)
}
test()

for 迴圈裡以 let 宣告

function test() {
  for (let i=0; i<10; i++) {
    console.log('i:', i)
  }
  console.log('Final value:', i)
}
test()

參考資源


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







Related Posts

[Tool] 7-Zip解壓縮簡中檔名為亂碼

[Tool] 7-Zip解壓縮簡中檔名為亂碼

NLP 新時代的開始 - BERT

NLP 新時代的開始 - BERT

JS註冊組|程式設計ABC|JavaScript&jQuery網站互動設計程式進化之道

JS註冊組|程式設計ABC|JavaScript&jQuery網站互動設計程式進化之道


Comments