首页 > 编程语言 >JavaScript works behind the scenes —— execution context(执行上下文)

JavaScript works behind the scenes —— execution context(执行上下文)

时间:2022-10-26 22:13:14浏览次数:47  
标签:execution const works JavaScript scenes second 上下文 context 执行

JavaScript works behind the scenes —— execution context(执行上下文)

What is execution context? 什么是执行上下文

Environment in which a piece of JavaScript is executed. Stores all the necessary information for some code to be executed.

代码执行的环境,存储着执行某些代码的必要信息。

What is inside execution context? 执行上下文中有什么

  1. Variable environment (变量环境)

let, const and var, declarations function, arguments object(NOT in arrow functions)

箭头函数的argument object 和 this 关键字都不包括在执行上下文中,因为箭头函数使用的argument object和this关键字都不是自身,是来自他们上一层的函数

  1. scope chain (作用域链)
  2. this keyword (this关键字)

以上的这些都在执行之前的“创建阶段”完成

image-20221010222901644

How the code exactly executed? 代码具体是怎么被执行的

example:

const name = 'kihyun'

const first = () => {
  let a = 1
  const b = second(7, 9)
  a = a + b
  return a
}

function second(x, y) {
  var c = 2
  return c
}

const x = first()
  1. 被编译好的代码开始执行

  2. 产生一个Global执行上下文,这个execution context被放入call stack中

    call stack: place where execution contexts get stacked on top of each other, to keep track of where we are in the execution.

    image-20221026215346829

  3. 第一行执行的代码是x = first(),此时产生first这个函数的execution context放入call stack中

    image-20221026215633193

  4. 此时执行的是first内的代码,执行到const b = second(7, 9)的时候,产生second函数的execution context放入call stack中

    image-20221026215831841

  5. 执行second内的代码,执行完毕后,return计算出的值,return之后对应的execution context从call stack中弹出

    image-20221026220029109

  6. second的execution context从call stack中弹出后,继续执行first中的代码

  7. 直到浏览器关闭Global的execution context才会被弹出

标签:execution,const,works,JavaScript,scenes,second,上下文,context,执行
From: https://www.cnblogs.com/kihyunBlog/p/16830276.html

相关文章