Web前端之路让前端飞程序员

JS作用域链

2017-07-25  本文已影响42人  07120665a058

作用域

function factory() {
     let name = 'person';
     let intro = function(){
          alert('I am ' + name);
     }
     return intro;
}
function app(para){
     let name = para;
     let func = factory();
     func();                  //'I am person'
}
app('people');

JavaScript中的函数运行在它们被定义的作用域里,而不是它们被执行的作用域里

作用域链

let x = 10;
function foo() {
   let y = 20;
   function bar() {
     let z = 30;
     alert(x +  y + z);
   }
   bar();
}
foo(); // 60

全局上下文的变量对象是

globalContext.VO === Global = {
  x: 10
  foo: <reference to function>
};

foo创建时,foo[[scope]]属性是

foo.[[Scope]] = [
  globalContext.VO     
];

foo激活时(进入上下文),foo上下文的活动对象是

fooContext.AO = {
  y: 20,
  bar: <reference to function>
};

所以,foo上下文的作用域链为

fooContext.Scope = fooContext.AO + foo.[[Scope]]  = [
  fooContext.AO,           //y=20
  globalContext.VO         //x=10
];

函数bar创建时,其[[scope]]

bar.[[Scope]] = [
  fooContext.AO,
  globalContext.VO
];

bar激活时,“bar”上下文的活动对象为

barContext.AO = {
  z: 30
};

bar上下文的作用域链为

barContext.Scope = barContext.AO + bar.[[Scope]] = [
  barContext.AO,            //x=30
  fooContext.AO,            //y=20
  globalContext.VO          //x=10
];

总结

参考文章推荐:
深入理解JavaScript系列(14):作用域链(Scope Chain)

上一篇 下一篇

猜你喜欢

热点阅读