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

JavaScript -- 执行上下文 #3

Open
mt51 opened this issue Oct 18, 2018 · 0 comments
Open

JavaScript -- 执行上下文 #3

mt51 opened this issue Oct 18, 2018 · 0 comments

Comments

@mt51
Copy link
Owner

mt51 commented Oct 18, 2018

执行上下文

可执行代码

可执行代码分为三类:全局代码,函数代码和eval代码。

当一段ECMAScript可以行代码被执行的时候,会进入到一个执行上下文。执行上下文(EC)是ECMA-262标准里面的一个抽象的概念。每个执行上下文都有三个重要的属性:

  • 变量对象(Variable Object, VO)
  • 作用域链(Scope chain)
  • this

执行上下文在逻辑上可以使用堆栈描述记为执行上下文栈,栈底永远是全局上下文,栈顶就是当前激活的执行上下文。堆栈在进入和退出上下文的时候被修改。

执行上下文栈

执行上下文栈用来描述代码在执行过程中激活的上下文环境。我们可以使用 ECStack = [] 来描述执行上下文栈。

当一段程序开始时,首先将全局上下文推入上下文栈中,随后程序开始执行会初始化一些函数和变量,初始化完成之后,在全局上下文环境中会调用一些函数。在函数执行的时候,会将自身的上下文环境推入执行上下文栈,在函数执行结束退出之后,执行上下文栈会将该函数的上下文环境从栈中弹出。在函数执行过程中我们可以使用return 或者是抛出异常来结束该执行上下文。

一个例子:

这里我们使用伪代码,用ECStack表示执行上下文栈

function foo() {
    console.log('foo')
}

function bar() {
   console.log('bar')
}

foo() // 'foo'
bar() // 'bar'

我们来分析一下这段代码的执行:

ECStack.push(globalContext) 
ECStack.push(<foo> functionContext)
ECStack.pop()
ECStack.push(<bar> functionContext)
ECStack.pop()

我们换个方式调用foobar

function foo() {
    console.log('foo')
    bar() // 'bar'
}

function bar() {
   console.log('bar')
}

foo() // 'foo'

此时,执行上下文栈的变化就和之前不一样了

ECStack.push(globalContext) 
ECStack.push(<foo> functionContext)
ECStack.push(<bar> functionContext)
ECStack.pop()
ECStack.pop()

出现这样变化的原因是,函数(caller)在执行过程中可以通过调用函数来激活另一个函数(caller)的上下文。我们可以这样描述这个过程:

caller 调用callee时会暂停自身的执行,将控制权交给callee,此时callee的上下文环境被推入栈中,当callee上下文结束后会把控制权交回caller,然后caller会从刚刚暂停的地方继续执行,此时callee的上下文环境会从栈中弹出。

参考

http://www.cnblogs.com/TomXu/archive/2012/01/13/2308101.html

http://www.cnblogs.com/TomXu/archive/2012/01/13/2308101.html

mqyqingfeng/Blog#4

@mt51 mt51 changed the title Javascript -- 执行上下文 JavaScript -- 执行上下文 Oct 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant