iT邦幫忙

0

Scope Chain & Closure

  • 分享至 

  • twitterImage
  •  

我們先來小試身手,在這之前我們必須有function scopeglobal varible的基本知識


let a = "hello"

function test1(){
    var a = "Goodbye"
    console.log(a) // Goodbye
    test2() 
}

function test2(){
        console.log(a) //hello
}
test1()

首先我們在全域定義 a = "hello",在function test1裡面又定義一次 a = "Goodbye",想當然爾function scope
就會輸出Goodbye,並且function test1 callback function test2,但是test2並沒有定義a ,那就會變成從全域變數找有沒有a的數值,並且找到 a = "hello!!!


接下來讓我們把function 改的複雜一點

let a = "Dennis"

function test1(){
    var a = "Jessica"
    console.log(a) //Jessica

    function test2(){
        console.log(a) //Jessica
    }

    function test3(){
        var a = "Jack"
        console.log(a) //Jack
        test2()
    }
    test3()
}


test1()

首先看到test1是一個function scope,定義 a = "Jessica"並且裡面有兩個function,function test3 call function test2,但function test3定義 a = "Jack",所以function test3會輸出"Jack",但是function test2 是function test1裡面的所以會抓取function test1的 a,最後輸出 "Jessica"


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言