JavaScript function scope/action chain domain/pre-parsing

Source: Internet
Author: User

On the scope and scope of the role of the problem, a lot of articles are very detailed, this article is an excerpt of their own feel that the value of the part, left by the use, only for reference, need to see the details please click on the original link I gave the original file

To be a loving Porter ~ ~

--------------------------------------------------------------------------------------------------------------- ----------------------------

Scope

JS in the scope of only one, is the function scope, in addition, there is a scope called block scope, but before this, want to say what is called a block

  Block

In Java or C (because I've only learned these two languages), a block is a statement written in {}, usually as a statement execution,

  Block scope (the concept of block scope does not exist in JS)

The statements in the block are closed outside the block, and in both Java and C there are features like this

For example

//JAVA Code Public classBlock { Public Static voidMain (string[] args) {if(true){            inti = 9; } System.out.println (i);//Code Error    }}//The above code compiles with an error, forcing compilation and execution to throw the following errors://Exception in thread "main" java.lang.Error:Unresolved//compilation problem:I cannot be resolved to a variable

So, Java is the concept of a block scope, the same code, when placed in JS

// JavaScript code function Fun () {        if(true) {                = 9;        }         return i;} Fun (); // Output 9

This means that the variables declared in the IF statement are left in memory after the IF statement and are not destroyed.

  In particular: JS, variables defined in the function with Var are local variables, variables defined without var are used by default as global variables

function F1 () {        var n=9;         = ten;  } F1 (); Console.log (n); // does not output the result, reported error: REFERENCEERROR:N is not defined, meaning that the variable is undefined console.log (m); // Output Ten

There are many articles about this, such as the block-level scope in javascript: The explanation of the scope in JS: when declaring a variable with the var keyword, the variable is automatically added to the closest available environment . For functions, this closest environment is the local environment of the function. If the variable is initialized without being declared, the variable is automatically added to the global environment.

Using effect of block scope in JS

Also in JavaScript to mimic block-level scopes This article uses anonymous functions to implement block scope functions

(function() {    // block-level scope });
From the original words: This technique is often used outside of functions in global scopes to limit the addition of too many variables and functions to the global scope. Of course, as long as we need some variables temporarily, we can use block-level scopes (private scopes). When the anonymous function finishes executing, its scope chain is destroyed immediately, thereby reducing the problem of closure resource utilization.

It's a good place to put a better description of scope knowledge. JS Scope problem Step-by-step thorough understanding

In this article, there is an example (this detail I didn't notice before >> details index:★★★★)

function Fun () {        var a = B = ten;} Console.log (a); // referenceerror:ais not defined console.log (b); // Output: Ten /* * Original words:  */

So I gave the following example myself.

function Fun () {        var a = ten, B = Ten;} Console.log (a); // referenceerror:ais not defined console.log (b); // referenceerror:b is not defined /* */

--------------------------------------------------------------------------------------------------------------- --------

Action Chain Field

Pre-parsing ( I want to say a question before I say the scope of the chain---pre-parsing, first give the address of the quoted article, convenient backtracking )

  Explain what is called pre-parsing (own name), hoping to give some beginners JS to provide some help

Argument: JS engine read a section of JS code, first pre-parse (the name I get up), is to read the JS code line by row, looking for global variables and global functions, encountered global variables, the value of the variable into Undefind, in memory, encountered global functions, directly in memory, the process if the syntax errors found , pre-parsing terminates.

When the pre-parsing is complete, the JS engine runs the JS code line by row starting from the first line.

  Pre-parsing of JS

Myth: JS's pre-parsing is when a program enters a new environment, the variables or functions in that environment are pre-parsed into the environment in which they can be called. That is, each pre-parsed unit is an execution environment.

Turn: JavaScript (JS) Pre-parsing principle

argument: function Pre-parse :

1. JavaScript performs a " pre-parsing " operation before execution: first creates an active object in the current execution environment, and sets the variables declared with VAR, defined functions as properties of the active object. But at this point the assignment of these variables is undefined.

2, in the JavaScript interpretation execution phase, when the variable needs to be parsed, it will be looked up from the active object of the current execution environment, if it is not found and the execution environment owner has the prototype attribute, it will be looked up from the prototype chain, otherwise it would be found by the scope chain. Encountered var a = ... Such a statement assigns a value to the corresponding variable (note: The assignment of the variable is done during the interpretation execution phase, and if the variable is used before it, its value will be undefined).

//Examples of preprocessingConsole.log (a);//Output: UndefinedConsole.log (b);//Output: UndefinedConsole.log (c);//output: Function C () {return "C";}varA = "a";varb =function(){returnB; }functionC () {return"C";}

//During the parsing phase, a saves the local variables that are declared with Var, and the default value is undefined, which is why the "Console.log (a)" output in the above code is undefined. Since the code has retained the marker a in the parsing phase, the assignment statement "var a =" a "; "The value of a before execution is undefined, so it appears as undefined at" Console.log (a) ". (Modify references from: (reprint) Talk about JavaScript closures and scope chains)

At this point, if the concept of pre-parsing is understood (in fact, I do not fully understand, the question is: The above example of the output of B and C why not the same??? If anyone understands, you can comment and tell me, appreciate it, you can say something about the scope of the chain.

Action Chain Field

Take a look at this article: (reprint) The closure and scope chain of JavaScript (this article tells a lot of the mechanism of things, personally feel better!!!)

The original: Scope chain (scope chain) is a chain consisting of scopes, and is a similar chain-like data structure. A scope is a data description of the context. Closures and scope chains are closely related, and closures at the execution of function instances are the basic elements that make up a chain of scopes. JavaScript code is parsed before execution, and in the parsing phase, variable declarations and function definitions in the global environment are recorded, and the calling object of the constructor (call Oject, Activation object, Activate object, Active object, different salutation) and the scope chain in the global environment.

[about the contents of the closure I will be in the next article in the JavaScript function of the closure, specifically]

As for the other knowledge points of the chain of action, I feel that there is no way to summarize than the article (reprint) of JavaScript and the scope of the closure of the chain is better, so, do not say, see the original!

--------------------------------------------------------------------------------------------------------------- -----------

Reference article:

Impersonation of block-level scopes in JavaScript

JS scope problem Step by step thorough understanding

Explain what is called pre-parsing (own name), hoping to give some beginners JS to provide some help

Pre-parsing of JS

Turn: JavaScript (JS) Pre-parsing principle

(reprint) on JavaScript closures and scope chains

JavaScript function scope/action chain domain/pre-parsing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.