Home  >  Article  >  Web Front-end  >  JavaScript Scope Chain Part 1: Scope Chain Definition

JavaScript Scope Chain Part 1: Scope Chain Definition

黄舟
黄舟Original
2016-12-20 16:16:351084browse

The data of an execution context (variables, function declarations, and function parameters) are stored as properties in the variable object. The variable object is created each time the context is entered and filled with the initial value. The update of the value occurs during the code execution phase.

This chapter is dedicated to discussing more details directly related to execution context. This time we will mention a topic - scope chain.

If you want to briefly describe and show the key points, then scope chain is mostly related to inner functions.

We know that ECMAScript allows the creation of inner functions, and we can even return these functions from the parent function.

var x = 10;
  
function foo() { 
  var y = 20; 
  function bar() {
    alert(x + y);
  } 
  return bar; 
}
  
foo()(); // 30

In this way, it is obvious that each context has its own variable object: for the global context, it is the global object itself; for the function, it is the active object.

The scope chain is just the list of all variable objects (including parent variable objects) in the inner context. This chain is used for variable query. That is, in the above example, the scope chain of the "bar" context includes AO(bar), AO(foo), and VO(global).

But let’s take a closer look at this issue.

Let’s start with the definition and discuss examples in depth.

A scope chain is associated with an execution context, and the chain of variable objects is used for variable lookup in identifier resolution.

The scope chain of the function context is created when the function is called, including the active object and the [[scope]] attribute inside this function. Below we will discuss the [[scope]] attribute of a function in more detail.

is represented in context as follows:

activeExecutionContext = {
    VO: {...}, // or AO
    this: thisValue,
    Scope: [ // Scope chain
      // 所有变量对象的列表
      // for identifiers lookup
    ]
};

Its scope is defined as follows:

Scope = AO + [[Scope]]

This union and identifier resolution process, which we will discuss below, is related to the life cycle of the function.

The above is the content of JavaScript scope chain one: scope chain definition. Scope chain one: scope chain definition content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
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