JS Function--scope

Source: Internet
Author: User
Tags variable scope

One: Related concepts of scope

First look at the concept of variable scope : The scope of a variable is the area in the program source code that defines the variable. ———————— Sixth edition of the JavaScript authoritative guide
Global variables have global scope, and local variables defined in the function body have function scopes.

As a personal understanding , scope (scope), as the name implies, is an area or field , and there are certain objects (including variables, properties, methods, etc.) that can work here; Scope is determined at the time of definition , and when it does not matter;

Question 1: Where is the area?

He is a concept that cannot be seen or touched; there is nothing in this area , but a concept execution context (EC) that is closely related to the scope, but he is in touch with the scope, which variables, parameters, This value is saved in context (the context is an object, variable arguments, etc. are saved as his attributes), the global scope corresponds to the global execution context, the function scope corresponds to the corresponding function execution contexts, and the context is generated at the time of execution of the code, stored in memory, variables in the context, etc. is its corresponding scope (global scope or function scope); See the next section, "Execution context."

Question 1: Who are some of the objects?
Who is defined in this area, and who is the object. Variable A is defined in the global scope and function fun is declared, then A and fun play a role in the global scope; the variable m is defined in the fun domain, then M plays in the fun domain (the variable A also works, and the principle can see the concept behind the scope chain); value, the current function parameter , and mainly contains these three types of objects.

Question 2: When do these objects work?

execution, when the global function executes, generate execution context, variables, etc., when the local function executes, generate function execution context, function body variables and so on; View the execution context in detail.

The JS variable has a down-transparent and up- close feature, which is transparent, which means that FUN,FN can access the global variable at the current scope A,FN can access the a,m, but in the function body, the local variable takes precedence over the same name as the ancestor variable. Closed up, which means that the global scope does not have access to the variable m in the fun domain, nor can it access the variables in the FN n,fun scope or access the variable n in his internal, nested FN field; a concept that relates to the scope chain (Scope chain): is an object A list or chain table that defines the variables in the scope of this code.

When there is no function definition in the global scope, there is only one object on the scope chain, the global object, which defines the relevant variable information; The general so-called chain, refers to a plurality of wear up is called chain, here is more special, is only one element of the chain.

When a global scope contains multiple nested functions, the scope chain becomes a linked list of multiple objects as function-level execution unfolds, and the linked list is dynamic, increasing and freeing memory as the code executes.

Visible, downward transparent, the principle of upward closure, such as the value of the B variable is a pointer, then in a domain, you can see the pointer value, and can not see the variable in the B field, so the B field is closed relative to the a field, that is, closed up; Speaking of which, is it a bit like closure? Closures are closed, only one interface (equivalent to a) to the outside world, there is nothing in the bag to let others directly see. The reason why JS can be closed is because of the storage mechanism-the variable is saved as a reference type! Closures are the case, whenever a function return value is a reference type, a closure is generated.

JS is a lexical-scoped language: You can know the scope of a variable by reading a number of lines of source code that contain variable definitions.

II: Classification of scopes

Scope can be divided into two types, global scope and function scope, function scope is created by the function, as for the global scope, we can also consider the global scope as a window function created, and this function only one, And all the code we write is within this function. So the bottom line: only functions can create scopes

Extension: What is the relationship between this global function and global functions such as Pareint ()?

The default global scope exists from the beginning of the code operation;

function scope:


All variables declared within a function are always visible in the body of the function .                          ,         &NB Sp                              
                           ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp        -------------Sixth edition of the JavaScript authoritative guide

Three points: all variables , always visible , defined

1. All variables ———— function parameters + function body variable + for loop/if statement/while statement variable

All of the variables listed in are the current function scope, the variables are transparent downward, and are closed up, both the FN2 function body can access the fun function and global variables, but global and fun is not directly accessible to the variables in fn2.

Note: A piece of code with braces, often referred to as code blocks , can be misleading in JS, and there is no block scope in JS, which is different from other programming languages (such as C, etc.). If you must use code blocks to understand, JS only recognizes the global code block and function code block as its scope.

For example, the following C + + code:

void Fun (int  x) {   int  A;                           The scope of variable A is in the function    fun for (int i=0;i<=; i++) { i++}      // Variable i in block-level scope for code block}

  

2, always visible —————— refers to the variable is available before writing the Declaration source code

The declaration in JS contains two declaration variable declarations (VAR) and function declarations (functions); When a variable is declared, only the variable name is defined, the type is undefined; when the function is declared, the function name is treated as a variable name, and the type is a function.

This feature is called the declaration in advance , that is, the declaration of all variables in the body of the current function (not involving assignment) code, are advanced to the top of the function body; in layman's words, it means that whenever a variable is declared in the body of a function, it can be accessed anywhere in the function body, regardless of where it is written. In fact, this is related to how the JS engine rules the execution of the code order, and he will first look for the keyword Var and function for the declaration to be saved in the execution context, which is done during the initialization phase of the execution context, and the assignment is

For example, execute the following code:

function fn () {console.log (a);        // underfined var a=3;}
fn ();

Equivalent to the following code:

function fn () {var A;                // variable declaration in advance Console.log (a);       // The default value is underfined a=3 when the variable is declared unassigned;}
FN ();

Question: When did the statement come in advance?

This involves another concept, the execution context, the Declaration of variables/functions is done at the time of code execution;

For example, the start of a file run, the creation of a global execution context, the generation of the environment is divided into two phases, namely the initialization phase + Assignment phase , then the declaration is included in the initialization phase in advance. See the next section for details.

3. There are definitions —————— variables are defined in the current function body

By definition, variables are defined in the body of any function that declares their function body and within the body of the function, and it can be seen that the variables defined in the current function body are effectively available in many nested functions, regardless of the function, including the number of layers of functions in the function body, which is the downward transparency feature mentioned above.

JS Function--scope

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.