[進階 js 04] Scope 變數的生存範圍


Posted by tzutzu858 on 2021-03-17

ES6 以前的作用域是 function 為基礎

一旦出了 function 就找不到
要找到只好設為全域變數,也就是放在 function 外

var a = 20 // global variable
function test() {
    var a = 10
    console.log(a)
}
test ()
console.log(a)

// 輸出 10 20

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

// 輸出 10 10

上面例子並沒有對 a 宣告 , 它會自動幫你在 global 宣告一個變數,然後值是 10


scope chain

var a = 'global'
function test() {
    var b = 'test scope b'
    console.log(a, b) // 印出 global test scope b

    function inner() {
    var b = 'inner scope b'
    console.log(a, b) // 印出 global inner scope b
    }
    inner()
}

test ()
console.log(a) // 印出 global

在第一次的 console.log(a, b),a 在 test 這層找不到,所以往上找,在 global 那層找到 a
在第二次的 console.log(a, b),a 在 inner 這層找不到,所以往上 test 找,找不到,在 global 那層找到 a
這個往上找就是 scope chain ,從 inner 找到 test 找到 global
但不要跟其他東西混淆
以下例子印出 a = ?

var a = 'global'
function change() {
    var a = 10
    test()
}

function test () {
    console.log(a)
}

change()

當初我以為是 10
結果正解出來是 global
scope 的概念跟你在哪邊呼叫 function 沒有關係,唯一關注是在那邊被宣告
所以並不是在 change 這個 function 執行 test() 就往上一行找 a
在上述例子 change 和 test 是兩個平行的 scope

正確 test scope -> global scope
錯誤 test scope -> change scope -> global scope

ES6 以後多了 letconst

用來宣告區塊裡的變數,只活在 { } 裡面
const constant 常數,一般使用不會重新指定值
let 一般使用可能會被重新指定值

複習 :[ JavaScript 12 ] ES6 新增特性










Related Posts

Git 筆記 - 將該次 commit 變動的檔案打包壓縮

Git 筆記 - 將該次 commit 變動的檔案打包壓縮

[第九週] MySQL 語法基礎

[第九週] MySQL 語法基礎

該如何入門 CTF 中的 Web 題?

該如何入門 CTF 中的 Web 題?


Comments