Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the JavaScript execution context and execution stack

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "what is the JavaScript execution context and execution stack". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

What is the execution context?

In short, execution context is an abstract concept of the environment in which JavaScript code is evaluated and executed. Whenever the JavaScript code is running, it runs in the context of execution.

Type of execution context

There are three execution context types in JavaScript.

Global execution context-this is the default or basic context, and any code that is not inside the function is in the global context. It does two things: create a global window object (in the case of the browser) and set the value of this to be equal to the global object. There is only one global execution context in a program.

Function execution context-every time a function is called, a new context is created for that function. Each function has its own execution context, but it is created when the function is called. There can be any number of function contexts. Each time a new execution context is created, it performs a series of steps in the defined order (discussed later).

Eval function execution context-the code that executes inside the eval function also has its own execution context, but since JavaScript developers don't use eval very often, I won't discuss it here.

Execution stack

The execution stack, also known as the "call stack" in other programming languages, is a data structure with LIFO (last-in, first-out) that is used to store all execution contexts created by the code runtime.

When the JavaScript engine first encounters your script, it creates a global execution context and pushes it into the current execution stack. Whenever the engine encounters a function call, it creates a new execution context for the function and pushes it onto the top of the stack.

The engine executes the function in the execution context at the top of the stack. When the function execution ends, the execution context pops up from the stack and controls the flow to the next context in the current stack.

Let's understand through the following code example:

Let a = 'Hello Worldworkers' functions first () {console.log ('Inside first function'); second (); console.log (' Again inside first function');} functionsecond () {console.log ('Inside second function');} first (); console.log (' Inside Global Execution Context')

When the above code is loaded in the browser, the JavaScript engine creates a global execution context and pushes it into the current execution stack. When a call to the first () function is encountered, the JavaScript engine creates a new execution context for the function and pushes it onto the top of the current execution stack.

When the second () function is called from inside the first () function, the JavaScript engine creates a new execution context for the second () function and pushes it into the top of the current execution stack. When the second () function finishes executing, its execution context pops up from the current stack, and the control flow reaches the next execution context, the execution context of the first () function.

When first () finishes executing, its execution context pops up from the stack, and the control flow reaches the global execution context. Once all the code has been executed, the JavaScript engine removes the global execution context from the current stack.

How do I create an execution context?

Now that we've seen how JavaScript manages the execution context, let's see how the JavaScript engine creates the execution context.

There are two phases in creating an execution context: 1) the creation phase and 2) the execution phase.

Creation Pha

The execution context goes through the creation phase before the JavaScript code is executed. Three things happen during the creation phase:

The determination of the this value, which is known as this binding.

Create lexical environment components.

Create variable environment components.

So the execution context is conceptually expressed as follows:

ExecutionContext = {ThisBinding =, LexicalEnvironment = {...}, VariableEnvironment = {...},} this binding: * *

In the context of global execution, the value of this points to the global object. (in the browser, this references the Window object).

In the context of function execution, the value of this depends on how the function is called. If it is called by a reference object, this will be set to that object, otherwise the value of this will be set to the global object or undefined (in strict mode). For example:

Let foo = {baz: function () {console.log (this);}} foo.baz (); / / 'this' reference' foo', because 'baz' is / / object' foo' calls let bar = foo.baz;bar (); / / 'this' points to the global window object because / / no reference object lexical environment is specified

The official ES6 documentation defines the lexical environment as

Lexical environment is a canonical type that defines the association between identifiers and specific variables and functions based on the lexical nesting structure of ECMAScript code. A lexical environment consists of an environment logger and a possible null value that references the outer lexical environment.

To put it simply, the lexical environment is a structure that holds an identifier-variable mapping. (the identifier here refers to the name of the variable / function, while the variable is a reference to the actual object [containing function type object] or raw data.)

Now, there are two components inside the lexical environment: (1) the environment logger and (2) a reference to an external environment.

The environment logger is the actual location where variables and function declarations are stored.

A reference to an external environment means that it can access its parent lexical environment (scope).

Translator's note: the external environment is already similar to the scope specified by ES3.

There are two types of lexical environment:

A global environment (in the context of global execution) is a lexical environment with no external environment references. The external environment reference to the global environment is null. It has built-in Object/Array/, etc., prototype functions in the environment logger (associated global objects, such as window objects), and any user-defined global variables, and the value of this points to the global object.

In a function environment, user-defined variables within the function are stored in the environment recorder. And the external environment referenced may be the global environment, or any external function that contains this internal function.

There are also two types of environmental recorders (as above! ):

The declarative environment logger stores variables, functions, and parameters.

The object environment logger is used to define the relationship between variables and functions that appear in the global context.

In short

In the global environment, the environment logger is the object environment logger.

In a functional environment, the environment logger is a declarative environment logger.

Note-for the functional environment, the declarative environment logger also contains an arguments object passed to the function (this object stores the mapping of indexes and parameters) and the length of the parameters passed to the function.

Abstractly, the lexical environment looks like this in pseudo-code:

GlobalExectionContext = {LexicalEnvironment: {Type: "Object", / / bind identifiers here} outer:}} FunctionExectionContext = {LexicalEnvironment: {EnvironmentRecord: {Type: "Declarative", / / bind identifiers here} outer:}} variable environment:

It is also a lexical environment in which the environment logger holds the binding relationship created by the variable declaration statement in the context of execution.

As mentioned above, the variable environment is also a lexical environment, so it has all the attributes of the lexical environment defined above.

In ES6, one difference between lexical environment components and variable environments is that the former is used to store function declarations and variable (let and const) bindings, while the latter is only used to store var variable bindings.

Let's take a look at the sample code to understand the above concept:

Let a = 20 × Const b = 30 * var c * function multiply (e, f) {var g = 20; return e * f * g;} c = multiply (20,30)

The execution context looks like this:

GlobalExectionContext = {ThisBinding:, LexicalEnvironment: {EnvironmentRecord: {Type: "Object", / / bind the identifier a:

< uninitialized >

, b:

< uninitialized >

, multiply:

< func >

} outer:}, VariableEnvironment: {EnvironmentRecord: {Type: "Object", / / bind identifiers c: undefined,} outer:}} FunctionExectionContext = {ThisBinding:, LexicalEnvironment: {EnvironmentRecord: {Type: "Declarative", / / bind identifiers here Arguments: {0: 20, 1: 30, length: 2},} Outer:}, VariableEnvironment: {EnvironmentRecord: {Type: "Declarative", / / bind identifiers g: undefined}, outer:}} here

Note-the function execution context is created only when the calling function multiply is encountered.

You may have noticed that the variables defined by let and const are not associated with any values, but the variables defined by var are set to undefined.

This is because during the creation phase, the engine examines the code to find variables and function declarations, which are stored entirely in the environment, but the variables are initially set to undefined (in the case of var) or uninitialized (in the case of let and const).

This is why you can access variables defined by var (though undefined) before declaration, but variables that access let and const before declaration will get a reference error.

This is what we call variable declaration promotion.

Execution phase

This is the simplest part of the whole article. At this stage, all of these variables are assigned, and finally the code is executed.

Note-at execution time, if the JavaScript engine cannot find the value of the let variable at the actual location declared in the source code, it will be assigned undefined.

This is the end of the content of "what is the JavaScript execution context and execution stack". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report