JavaScript Hoisting

weixin_33912246發表於2017-06-01

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

function number() {
    return 1;
}

(function() {
    try {
        number();
    } catch (ex) {
        console.log(ex);
    }
    var number = function number() {
        return 2;
    };

    console.log(number());
})();

console.log(number());

js會把宣告提升到當前作用域的最上邊,包括變數和函式宣告。

function number() {
    return 1;
}

(function() {
    console.log(number());

    function number() {
        return 2;
    }
})();

console.log(number());

相關文章