變數/函式宣告將被提至該生命區塊的開端(hoisting)

var str = "global"; //全域變數
function f () { //全域函式
    return "global function";
}

function hoistMe(){
    alert(str); //undefined
    alert(f()); //local function
    var str = "local"; //宣告 hoist
    function f(){ //宣告&實做 都 hoist
        return "local function";
    }
}

hoistMe();


你可能會以為第一個alert彈出的是"global",第二個彈出"global function"

事實上...第一個alert會彈出"undefined",第二個彈出"local function"
是因為變數/函式宣告將被提至該生命區塊的開端,實際運作如下:

function hoistMe(){

    var str;//宣告 hoist
    function f(){ //宣告&實做 都 hoist
        return "local function";
    }
    
    alert(str); //undefined
    alert(f()); //local function
    
    str = "local";
    // f() hoist 到上面去了/...
}

因此,為了避免這種混亂,最好是預先宣告你想使用的全部變數/函式。

arrow
arrow
    全站熱搜

    vivian 發表在 痞客邦 留言(0) 人氣()