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

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!