当前位置:首页 >> 网络编程

JavaScript 中的执行上下文和执行栈实例讲解

JavaScript - 原理系列

"htmlcode">

// 递归调用自身
function foo() {
  foo();
}
foo();
// 报错:Uncaught RangeError: Maximum call stack size exceeded

Tips:

"text-align: center;">JavaScript 中的执行上下文和执行栈实例讲解

现在让我们用一段代码来理解执行栈

let a = 'Hello World!';

function first() {
 console.log('Inside first function');
 second();
 console.log('Again inside first function');
}

function second() {
 console.log('Inside second function');
}

first();
console.log('Inside Global Execution Context');

下图是上面代码的执行栈

JavaScript 中的执行上下文和执行栈实例讲解

"htmlcode">

ExecutionContext = {
 ThisBinding = <this value>,
 LexicalEnvironment = { ... },
 VariableEnvironment = { ... },
}

This 绑定:

"htmlcode">

let foo = {
 baz: function() {
 console.log(this);
 }
}
foo.baz();  // 'this' 引用 'foo', 因为 'baz' 被
       // 对象 'foo' 调用
let bar = foo.baz;
bar();    // 'this' 指向全局 window 对象,因为
       // 没有指定引用对象

词法环境

官方的 ES6 文档把词法环境定义为

"htmlcode">

GlobalExectionContext = {
 LexicalEnvironment: {
  EnvironmentRecord: {
   Type: "Object",
   // 在这里绑定标识符
  }
  outer: <null>
 }
}

FunctionExectionContext = {
 LexicalEnvironment: {
  EnvironmentRecord: {
   Type: "Declarative",
   // 在这里绑定标识符
  }
  outer: <Global or outer function environment reference>
 }
}

变量环境:

"htmlcode">

let a = 20;const b = 30;var c;
function multiply(e, f) { var g = 20; return e * f * g;}
c = multiply(20, 30);

执行上下文看起来像这样:

GlobalExectionContext = {

 ThisBinding: <Global Object>,

 LexicalEnvironment: {
  EnvironmentRecord: {
   Type: "Object",
   // 在这里绑定标识符
   a: < uninitialized >,
   b: < uninitialized >,
   multiply: < func >
  }
  outer: <null>
 },

 VariableEnvironment: {
  EnvironmentRecord: {
   Type: "Object",
   // 在这里绑定标识符
   c: undefined,
  }
  outer: <null>
 }
}

FunctionExectionContext = {
 ThisBinding: <Global Object>,

 LexicalEnvironment: {
  EnvironmentRecord: {
   Type: "Declarative",
   // 在这里绑定标识符
   Arguments: {0: 20, 1: 30, length: 2},
  },
  outer: <GlobalLexicalEnvironment>
 },

VariableEnvironment: {
  EnvironmentRecord: {
   Type: "Declarative",
   // 在这里绑定标识符
   g: undefined
  },
  outer: <GlobalLexicalEnvironment>
 }
}

注意

"https://juejin.cn/post/6844903682283143181" rel="external nofollow" target="_blank">https://juejin.cn/post/6844903682283143181

https://www.jianshu.com/p/6f8556b10379

https://juejin.cn/post/6844903704466833421