Home > Web Front-end > JS Tutorial > body text

A cliché about native JS execution environment and scope

高洛峰
Release: 2016-12-06 09:56:16
Original
1298 people have browsed it

First of all, we need to know that execution environment and scope are two completely different concepts.

Every call to a function has a scope and execution environment closely related to it. Fundamentally speaking, scope is based on functions, while execution environment is based on objects (for example: the global execution environment is the window object).

In other words, the scope involves variable access in the called function, and different calling scenarios are different. The execution environment is always the value of the this keyword, which is a reference to the object that owns the currently executing code. Each execution environment has a variable object associated with it, and all variables and functions defined in the environment are stored in this object. Although the code we write has no access to this object, the parser uses it behind the scenes when processing the data.

Execution environment (also called execution context – execution context)

When the JavaScript interpreter initializes the execution code, it first enters the global execution environment by default. From this point on, each call to the function will create a new execution environment.

Each function has its own execution environment. When the execution flow enters a function, the function's environment is pushed into an execution stack. After the function is executed, the stack pops its environment and returns control to the previous execution environment. The execution flow in ECMAScript programs is controlled by this convenient mechanism.

The execution environment can be divided into two stages: creation and execution. In the creation phase, the parser first creates a variable object (also called an activation object), which consists of variables, function declarations, and parameters defined in the execution environment. At this stage, the scope chain will be initialized and the value of this will be finalized. During the execution phase, the code is interpreted and executed.

Demo:

<script type="text/javascript">
  function Fn1(){
    function Fn2(){
      alert(document.body.tagName);//BODY
      //other code...
    }
    Fn2();
  }
  Fn1();
  //code here
</script>
Copy after login

A cliché about native JS execution environment and scope

Summary

When the javascript code is loaded by the browser, the first thing it enters by default is a global execution environment. When a function is called and executed in the global execution environment, the program flow enters the called function. At this time, the JS engine will create a new execution environment for the function and push it to the top of the execution environment stack. The browser always executes the execution environment currently at the top of the stack. Once execution is completed, the execution environment will be popped from the top of the stack, and then enter the execution environment below it to execute the code. In this way, the execution environments in the stack will be executed sequentially and popped from the stack until returning to the global execution environment.

In addition, please note a few points:

Single thread

Synchronous execution

The only global execution environment

There is no limit to the number of local execution environments

Every time a function is called, there will be a new one A local execution environment is created for it, even if its own function is called multiple times (that is, if a function is called multiple times, multiple different local execution environments will be created).

Scope

When code is executed in an environment, a scope chain of variable objects is created. The purpose of a scope chain is to ensure ordered access to all variables and functions that the execution environment has access to.

The scope chain contains the variable objects corresponding to each execution environment in the execution environment stack. Through the scope chain, you can determine the access of variables and the resolution of identifiers.

Note: The variable object of the global execution environment is always the last object in the scope chain.

When accessing variables, there must be a visibility issue (the inner environment can access the variables and functions in the outer layer, but the outer environment cannot access the variables and functions in the inner layer). To go deeper, when accessing a variable or calling a function, the JavaScript engine constructs a linked list from variable objects in different execution environments according to rules. When accessing a variable, it first searches on the first variable object in the linked list. If If not found, continue searching on the second variable object until the variable object of the global execution environment, that is, the window object is found. This also forms the concept of Scope Chain.

A cliché about native JS execution environment and scope

The scope chain diagram clearly expresses the relationship between the execution environment and the scope (one-to-one correspondence), and the relationship between scopes (linked list structure, top-to-bottom relationship).

Demo:

var color = "blue";
function changeColor(){
 var anotherColor = "red";
 function swapColors(){
  var tempColor = anotherColor;
  anotherColor = color;
  color = tempColor;
  // 这里可以访问color, anotherColor, 和 tempColor
 }
 // 这里可以访问color 和 anotherColor,但是不能访问 tempColor
 swapColors();
}
changeColor();
// 这里只能访问color
console.log("Color is now " + color);
Copy after login

The above code includes a total of three execution environments: the global execution environment, the local execution environment of changeColor(), and the local execution environment of swapColors().

The global environment has a variable color and a function changecolor(); The local environment of the

changecolor() function has an anothercolor attribute and a swapcolors function. Of course, the changecolor function can access itself and its surroundings (ie, the global environment) The variable in;

swapcolor() function has a variable tempcolor in the local environment. All variables in the above two environments (changecolor and window) can be accessed inside this function, because those two environments are its parent execution environments.

The scope chain of the above code is as shown below:

A cliché about native JS execution environment and scope

从上图发现。内部环境可以通过作用域链访问所有的外部环境,但是外部环境不能访问内部环境中的任何变量和函数。

标识符解析(变量名或函数名搜索)是沿着作用域链一级一级地搜索标识符的过程。搜索过程始终从作用域链的前端开始,然后逐级地向后(全局执行环境)回溯,直到找到标识符为止。

执行环境与作用域的区别与联系

执行环境为全局执行环境和局部执行环境,局部执行环境是函数执行过程中创建的。

作用域链是基于执行环境的变量对象的,由所有执行环境的变量对象(对于函数而言是活动对象,因为在函数执行环境中,变量对象是不能直接访问的,此时由活动对象(activation object,缩写为AO)扮演VO(变量对象)的角色。)共同组成。

当代码在一个环境中执行时,会创建变量对象的一个作用域链。作用域链的用途:是保证对执行环境有权访问的所有变量和函数的有序访问。作用域链的前端,始终都是当前执行的代码所在环境的变量对象。

小练习

<script type="text/javascript">
(function(){
  a= 5;
  console.log(window.a);//undefined
  var a = 1;//这里会发生变量声明提升
  console.log(a);//1
})();
</script>
Copy after login

window.a之所以是undefined,是因为var a = 1;发生了变量声明提升。相当于如下代码:

<script type="text/javascript">
(function(){
  var a;//a是局部变量
  a = 5;//这里局部环境中有a,就不会找全局中的
  console.log(window.a);//undefined
  a = 1;//这里会发生变量声明提升
  console.log(a);//1
})();
</script>
Copy after login

   


Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!