JS Closing Packet Summary

Source: Internet
Author: User

1. Variables are defined in the body of any function that declares their function body and is nested within the function body. eg

Alert (TMP);

var tmp=123;// not defined without error

2. A classic example of a scope chain:

Name= "Lwy";

Functiont () {

var name= "Tlwy";

function S () {

var name= "Slwy";

Console.log (name);

}

function SS () {

Console.log (name);

}

S ();

SS ();

}

T ();

in the preceding code , the first outputis Slwy, the second output is Tlwy, because when JS is executed, the execution environment (the calling object) of the function is created, and the object is placed at the beginning of the list. It then links the calling object of the function, and finally the global object. Then looking for the variable name from the beginning of the list, it is obvious that name is "Slwy".

however , when the SS () is executed, the scope chain is:SS()->t ()->window, so name is "Tlwy".

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/4B/CE/wKioL1Qz-u-Sr18CAAFyI5w-UsU569.jpg "title=" 1 (1). PNG "alt=" wkiol1qz-u-sr18caafyi5w-usu569.jpg "/>

when it comes to scope chains, you have to say with statements. the with statement is primarily used to temporarily extend the scope chain, adding objects in the statement to the scope's head. eg:

Person={name: "Yhb", Age:22,height:175,wife:{name: "Lwy", age:21}};

With (Person.wife) {

Console.log (name);

}

The WITH statement adds Person.wife to the part of the scope chain, so the output is:"Lwy";

after the With statement ends, the scope chain returns to normal. Obviously the with statement has a performance problem with the process of copy and moving objects to the head of the scope.

3. Scope Chain : A simple scope chain is a function created at the time of definition, used to find an index of the value of the variable used, and his internal rule is to put the local variables of the function itself in the first place, put the variables in the parent function in the second, put the variables in the higher-level function later, Until the global object is followed. When the function needs to query the value of a variable,the JS interpreter will go to the scope chain to find, from the first local variables to find, if not found the corresponding variable, then to the next level of the scope chain to find, once the variable is found, it will no longer continue. If the desired variable is not found at the end, the interpreter returns undefined.

4. Closures : Understand the scope chain, and then look at JS Memory recovery mechanism, in general, a function at the time of execution, it will be defined in the variable memory space to save, in case of the subsequent statements to use, wait until the function is completed return, these variables are considered useless, The corresponding inner space is also recycled. The next time you execute this function, all the variables return to their original state and are re-assigned to use. But if another function is nested inside the function, and this function is likely to be called externally, and the inner function uses some of the variables of the external function. This memory-recycling mechanism can cause problems. If an intrinsic function is called directly after the external function is returned, the intrinsic function cannot read the value of the variable in the external function that he needs. So when the JS interpreter encounters a function definition, it automatically saves the function along with the variables he might use, including the local variables and the variables (free variables) of the parent and ancestor functions. That is, building a closure, these variables will not be recycled by the memory collector, only if the internal function is not possible to be called after (for example, deleted, or without a pointer), the closure will be destroyed. That is, when no one of the closure reference variables exists, it is recycled when the next memory recycle starts.

In other words, with closures, nested function structures work, which is what we expect. eg:

Varresult=[];

Functionfoo () {

var i= 0;

for (; i<3;i=i+1) {

Result[i]=function () {

Alert (i)

}

}

};

Foo ();

Result[0] ();//3

RESULT[1] ();//3

RESULT[2] (); 3

in this code, the programmer wants the variable i in the Foo function to be used by the internal function, and can get their index separately, but in fact, only the last value that the variable is retained, that is, the free variable of all the records in the closure, Just a reference to the variable, not the value of the variable, when the variable is changed, the value of the variable obtained in the closure will also be changed.

One way to do this is to have the inner function be executed as soon as the loop is created, and capture the current index value and record it in one of its own local variables. Then, using the return function method, rewrite the intrinsic function, let the next call, return the value of the local variable, the improved code:

Varresult=[];

Functionfoo () {

var i= 0;

for (; i<3;i=i+1) {

Result[i]= (function (j) {

return function () {

Alert (j);

};

}) (i);

}

};

Foo ();

Result[0] ();//0

RESULT[1] ();//1

RESULT[2] (); 2

5. Closures are functions inside functions, essentially closures are a bridge linking functions inside and outside the function.

6. Closure function: One can read the variables inside the function, and the other is to keep these variables in memory at all times

7. Issues to note with closures

1) because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may cause memory leaks. The workaround is to remove all unused local variables before exiting the function.

2) The closure changes the value of the inner variable of the parent function outside the parent function. Therefore, if the parent function is used as an object, the closure as its common method, and the internal variable as its private property, you must be careful not to arbitrarily change the value of the parent function variable.

8. Closures : is an environment expression (usually a function) that has many variables and binds them, so these variables are also part of the expression, which, in layman's terms, is the function in all JavaScript is a closed package. In general, however, the nested function produces a more powerful closure, which is what we call "closures" most of the time.

When the function's intrinsic function is referenced by a variable outside the function, a closure is created. A closure is a method function that defines another function as the target object in the body of the re-constructor, which in turn refers to the temporary variable in the outer function body. This makes it possible to indirectly maintain the value of temporary variables used by the original constructor body as long as the target object is always able to maintain its methods over the lifetime. Although the initial constructor call has ended, the name of the temporary variable disappears, but the value of the variable is always referenced inside the method of the target object, and that value can only be accessed through this method. Even if the same constructor is called again. But only new objects and methods are generated, and the new temporary variables only correspond to the new values, and the last time the call was separate.

9. Bottom-up explanation of closures : For a function

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/4B/CC/wKiom1Qz-rnT8kPaAABMJflS3mU332.jpg "title=" 1 (2). PNG "style=" Float:none; "alt=" wkiom1qz-rnt8kpaaabmjfls3mu332.jpg "/>

when defining function a ,the JS interpreter sets the scope chain (scopechain) of function a to the "environment" where A is located when A is defined , if a is a global function, only the Window object is in scope chain .

when the function A is executed ,a is entered into the appropriate execution environment (excutioncontext).

During the creation of the execution environment, a scope property, the scope of a, is first added for a, and its value is the scope chain in step 1. That is , the scope chain of the a.scope=a.

The execution environment then creates an active object (Call object) . The active object is also an object with properties, but it does not have a prototype and is not directly accessible through JavaScript code. After the active object is created, add the active object to the top of the scope chain of a. At this point a 's scope chain contains two objects:a 's active object and the window object.

The next step is to add a arguments property on the active object , which holds the arguments passed when the function A is called.

finally all functions a B b 3 step, function b the environment defined, that is, a< Span style= "font-family: ' The song Body '; The scope of the.

to this, the entire function a a return function b reference to C a The active object, i.e. b You can access all the variables and functions defined in a b c reference, function B a will not be gc< after return Span style= "font-family: ' The song Body '; > recycling.

when function b executes, it will be the same as the above steps. Therefore, the scope chain of execution B contains 3 objects:The active objectof B, the active object of A, and the window object, as shown in:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/4B/CC/wKiom1Qz-rizziYDAADlxLSZKWQ226.jpg "title=" 1 (1). JPG "style=" float:none; "alt=" wkiom1qz-rizziydaadlxlszkwq226.jpg "/>

, when a variable is accessed in function B, the search order is:

Searches for the active object itself first, if it exists, returns if there is no active object that will continue to search for function A, and then finds it until it is found.

if the prototype prototype object exists in function B, it finds its own prototype object after it finds its own active object, and then continues to look for it. This is the variable lookup mechanism in Javascript.

returns undefined if none of the entire scope chain is found .

There are two important words mentioned above: the definition and execution of a function. It is mentioned in the article that the scope of the function is determined when the function is defined, not when it is executed (see steps 1 and 3). Use a piece of code to illustrate the problem:

function f (x) {

var g = function () {RETURNX;}

return g;

}

var h = f (1);

Alert (H ());

The variable h in this code points to the anonymous function ( returned by G) in F.

assuming that the scope of the function h is determined by the execution alert (H ()) , then the scope chain of H is:h 's active object ->alert The->window object for the active object .

assuming that the scope of the function H is defined at the time of definition, the anonymous function pointed to by H has been scoped at the time of definition. Then, at execution time,the scope chain of H is:H 's active object->f the active object->window object.

If the first hypothesis is true, the output value is undefined; If the second hypothesis is true, the output value is 1.

The result of the operation proves that the first 2 assumptions are correct, stating that the scope of the function is indeed defined when defining the function.

10. The role of closures:

1) Security of variables within the protection function.

2) maintain a variable in memory.

3) JS private Properties and Private methods are implemented through the security of the protection variables


This article is from "Tiger Brother's Blog" blog, please be sure to keep this source http://7613577.blog.51cto.com/7603577/1561087

JS Closing Packet Summary

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.