深刻理解javascript 執行上下文和執行棧

var foo = function () {

    console.log('foo1');

}

foo();  // foo1

var foo = function () {

    console.log('foo2');

}

foo(); // foo2

複製代碼

function foo() {

    console.log('foo1');

}

foo();  // foo2

function foo() {

    console.log('foo2');

}

foo(); // foo2複製代碼

JavaScript 引擎並不是一行一行地分析和執行程序,而是一段一段地分析執行。當執行一段代碼的時候,會進行一個「準備工做」,好比第一個例子中的變量提高,和第二個例子中的函數提高。
git

function test(arg) {
    // 1. 形參 arg 是 "hi"
    // 2. 由於函數聲明比變量聲明優先級高,因此此時 arg 是 function
    console.log(arg);
    var arg = "hello"; // 3.var arg 變量聲明被忽略, arg = 'hello'被執行
    function arg() {
        console.log("hello world");
    }
    console.log(arg);
}
test("hi");
/* 輸出:
function arg(){
    console.log('hello world') 
    }
hello 
*/複製代碼

參考文章:github

chorer.github.io/2019/04/10/…
bash

相關文章
相關標籤/搜索