1. 程式人生 > >function內,var a = b = 1; b 為什麼會是全域性變數?

function內,var a = b = 1; b 為什麼會是全域性變數?

為什麼在函式一中,只有變數a被宣告?
因為賦值是從右向左結合:

var a=b=c=d=5; 等價於 var a=(b=(c=(d=5)));,其中只有a被聲明瞭,b,c和d都是自動解析為全域性變量了。

(function tt() {
        var a=b=c=d=5;
        console.log(typeof a) //number
        console.log(typeof b) //number
        console.log(typeof c) //number
        console.log(typeof d) //number

    })()
    console.log(typeof a) //undefined
    console.log(typeof b) //number