首页 > 编程语言 >JavaScript works behind the scenes —— scope and scope chain(作用域和作用域链)

JavaScript works behind the scenes —— scope and scope chain(作用域和作用域链)

时间:2022-10-27 00:33:39浏览次数:42  
标签:变量 chain 作用域 scenes behind scope

JavaScript works behind the scenes —— scope and scope chain(作用域和作用域链)

what is scope? (作用域的概念)

Scope: Space and environment in which a certain variable is declared. There is global scope, function scope, and block scope.

(作用域: 一个变量被声明的位置和环境。有全局作用域,函数作用域,块级作用域)

3 kinds of scope(3种作用域)

  1. global scope 全局作用域,在哪儿都能访问
  2. function scope 函数作用域,只有在函数种可以访问
  3. block scope 块级作用域,let和const定义的变量的作用域

what is scope chain? (作用域链的概念)

If one scope needs to use a certain variable, but cannot find it in the current scope, it will look up in the scope chain and see if it can find a variable in one of the parent scopes.

(如果一个作用域需要用到某一个变量,但是在当前的作用域找不到,会沿着作用域链去找这个变量是否存在于父作用域。)

各个作用域之间并没有向下复制变量,因为子作用域可以沿着作用域链访问到上层的变量,所以相对来说作用域是逐渐变大的。但是同等级的两个作用域之间是互相不可访问的。

image-20221026232422195

scope chain VS call stack

call stack是垂直的,每个execution context之间并没有直接关系,是一种程序执行的顺序。

作用域链是有层级关系的,两个作用域之间可以是上下层关系,也可以是平行的关系。

image-20221026232714416

标签:变量,chain,作用域,scenes,behind,scope
From: https://www.cnblogs.com/kihyunBlog/p/16830654.html

相关文章