Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

执行上下文栈 #1

Open
AngellinaZ opened this issue Feb 8, 2018 · 0 comments
Open

执行上下文栈 #1

AngellinaZ opened this issue Feb 8, 2018 · 0 comments

Comments

@AngellinaZ
Copy link
Owner

AngellinaZ commented Feb 8, 2018

参考连接:JavaScript深入之执行上下文栈, by冴羽

js代码执行顺序

顺序执行,但 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

可执行代码 (executable code)

三种: 全局代码, 函数代码, eval代码(不推荐使用)

当要执行一个函数时,会进行准备工作 (创建一个执行上下文)

执行上下文栈 (Execution context stack,ECS)

当执行一个函数的时候,就会创建一个执行上下文,并且压入执行上下文栈,当函数执行完毕的时候,就会将函数的执行上下文从栈中弹出。

执行上下文栈 模拟 --创建数组 ECStack = [ ]
开始执行,最先遇到全局代码,初始化的时候首先向 ECStack.push (globalContext ),并且只有当整个应用程序结束的时候,ECStack 才会被清空

ECStack = [
    globalContext
];
  • 例子1
var scope = "global scope";
function checkscope(){
    var scope = "local scope";
    function f(){
        return scope;
    }
    return f();
}
checkscope();  // local scope
// 过程模拟
ECStack.push(<checkscope>functionContent)
ECStack.push(<f>functionContent)
ECStack.pop()
ECStack.pop()
  • 例子2
var scope = "global scope";
function checkscope(){
    var scope = "local scope";
    function f(){
        return scope;
    }
    return f;
}
checkscope()();  // local scope
// 过程模拟
ECStack.push(<checkscope>functionContent)
ECStack.pop()
ECStack.push(<f>functionContent)
ECStack.pop()
@AngellinaZ AngellinaZ reopened this Apr 2, 2018
@AngellinaZ AngellinaZ changed the title 学习总结の执行上下文栈 执行上下文栈 Jun 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant