Home Web Front-end JS Tutorial A cliché about native JS execution environment and scope

A cliché about native JS execution environment and scope

Dec 06, 2016 am 09:56 AM
js

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

   


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles