关于JS作用域链

2018-03-29  本文已影响0人  jrg_tzc

执行上下文

JavaScript引擎并不是一行一行的分析代码,而是一段一段的。在代码运行之前会进行内存分配,代码上下文关联的准备。我把这理解成执行上下文。
上下文主要有三个属性

activeExecutionContext == {
  VO : {...},  // or AO
  this: thisValue,
  Scope: [...]
}

其中VO或AO是变量对象,this为this指针,scope便为作用域链。

作用域链

每个上下文都有自己的变量对象。作用域链便是上下文中所有变量对象的列表,与执行上下文相关。可用于在标识符解析中变量查找。
举个例子,当这段代码执行时

var x = 10;
bar() 
function bar(){
  var x = 30;
  function foo(){
    console.log(x) 
  }
  foo();
}

全局上下文的变量对象是:

globalContext.VO == {
  x: 10
  bar: <reference to function>
}

bar被调用后的上下文活动对象:

barContext.AO == {
  x: 30
  foo: <reference to function>
}

bar的上下文作用域链便为:

barContext.Scope == [
  barContext.AO,
  globalContext.VO
]

而接着foo被调用后其作用域链便为

fooContext.Scope == [
  fooContext.AO,
  barContext.AO,
  globalContext.VO
]

当解析a标识符时,便依据作用域链去查找。

  fooContext.AO   // not found
  barContext.AO  //  found - 30
  globalContext.VO 

在bar的变量对象中找到30,便停止查找,返回30.

上一篇 下一篇

猜你喜欢

热点阅读