JS Closures and scope chains

Source: Internet
Author: User
Tags variable scope

Closed Package

Closed Package

function objects can be associated with each other through the scope chain, and variables inside the function body can be stored within the scope of the function.

This feature is called "closures".

What is a variable?

A variable is a name assigned to all things ;

the function of Var, initializes the variable.

Variable scope

The area where the variable is defined in the source code of the program is the variable scope. ( where is the name? )

Global variables have global scope and are defined everywhere in the JS code. (the name is very loud)

The variables declared in the function body are valid in the function body, they are local variables, function arguments are local variables, they are defined only in the function body. ( the inner layer can get the value of the outer layers, the outer layer is not able to get the value of the innermost)

In a function body, a local variable with the same name takes precedence over a global variable of the same name, and the function parameter is also a local variable.

Example 1: var scopte = "Gloabl";

function Checkscope () {

var scope = "local";

return scope;

}

Checkscope ()//"local";

Example 2:var attri = 100; Global variables have the same name as function arguments, and global variables are obscured.
function Fuck (Attri) {
alert (Attri);
}
Fuck (10);//10

Example 3:

var scope = "Global scope";
function Checkscope () {
var scope = "local scope";
function nested () {
var scope = "Nested scope";
return scope;
}
return nested ();
}
Checkscope ();//"nested";

There is no block-level scope in JS, instead it is the function scope.

Variables are defined in the body of the declared function and in any function within which the body of the function is nested.

Declaration in advance ( the place where Var is encountered is declared in advance)

Example 4:

function Test (o) {

/*i are defined in the entire body of the function * /
var i = 0;
if (typeof o== "Object") {

/*j is defined in the function body, not just in this code segment * /
var j=0;

/*k is defined in the body of the function, not just within the loop * /

for (var k=0; k<10;k++) {
Console.log (k); output 0~9
}
Console.log (k); 10
}
Console.log (j); J has been defined, but may not be initialized.
}

Equivalent to

function Test (o) {
var i;
var J;
var k;
i = 0;
if (typeof o== "Object") {
j=0;
for (k=0; k<10;k++) {
Console.log (k);
}
Console.log (k);
}
Console.log (j);

Example 5:

var scope = "global";
function f () {
Console.log (scope); //calledf ()Outputundefineddeclaration in advance
var scope = "local"; //Although not the first line of code, the actualScopehas been declared.
Console.log (scope)//calledf ()OutputLocal;
}

Equivalent to

var scope = "global";

function f () {

var scope;

Console.log (scope);

Scope = "local";

Console.log (scope); JS has no block-level scope and is replaced by a function scope.

}

Scope Chain (scope chain is a special list of objects object-list )

Defining a function is the creation of a scope object, which creates a scope object that consists of a scoped chain.

What code to declare when talking about scopes. Just like when we are someone, we need to explain who it is. 0

Each piece of JavaScript Code has a scope chain associated with it , ( There is no block-level scope in JS, instead the scope of the function.) This scope chain is a list of objects. Objects in this code scope are defined in the object list.

var creates a variable that is not configurable and cannot be deleted by the delete operator.

Global variables are always defined in a program, and local variables are always defined in the declared function body and within the nested function body.

If you consider a local variable as a property of a custom object, you can interpret the scope of the variable at a different angle, eachJSthe code has a scope chain associated with it, and the scope chain is aObject List (object-list), Object-listdefines the variables in the scope of this code. WhenJSvariable Requiredx(this time it is calledVariable parsing), which will beobject-listThe first object in the start lookup, if the variable is usedxis used directly, without looking for the nextobject-listThe next object in the query, if all theobject-listThere are no objects in thexthis variable, a reference error is thrown.

Scope Chain Type

(1) in the top-level code of JS (without any code within the function definition), the stored scope chain consists of 1 global objects.

(2) In the definition does not contain nested function body, the scope chain of the preservation is composed of 2 objects, the 1 object is the definition function parameter and the local variable composition, 2 is a global object.

(3) in the definition of a nested function body, the stored scope chain contains at least 3 objects, and the 1 is an object consisting of parameters and local variables within the nested function, and section 2 An object is a parameter of an outer function and a local variable, and the 3 object is a global object.

Creating rules for scope chains

When you define afunctionwhen, thisfunctionactually preserves a scope chainobject-list, when calling thisfunctionwhen, thisfunctionCreate a newObject(Similar to creating objects through constructors) to save its own local variables,then this creates theObjectadd to the saved scope chainobject-liston, the originalobject-listAn object is added,

function A () {var C;}// When creating this function, a object-list is saved

A ()// Call this function to create a new object to save its own local variables, and add this object to the scope chain object-list , Make the scope chain longer when the function is defined, and then create a new "chain" that represents the scope of the function call.

Example 7:

var i = 0;

/* When defining this function , there are 2 scope chains object-1 empty,object-2 There is var i this variable value. */
function A () {

i++;
alert (i);
}

/* when calling this function, a variable object is created to change The scope chain when defining function,object-1 is empty, Object-2var i change * /
A (); 1
A ();//2

For nested functions, each time an external function is called, the scope chain that defines the external function becomes longer, so the scope chain of the inner nested function is subtly different each time. The nested inner function scope consists of the scope chain of the outer function, the scope of the outer function changes, and the scope chain of the inner function begins to change.

What is the meaning of calling a function?

JS Closures and scope chains

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.