What is the "closure" of JavaScript? (2) javascript

Source: Internet
Author: User

What is the "closure" of JavaScript? (2) javascript

The title of my previous blog is incorrect, causing some misunderstandings. I think the purpose of a blog is not to back up textbooks, but to share the R & D experience. The title of my previous article should be changed to"JavaScriptA topic of closure: it applies to outer scopeImpact", Because I did not strictly analyze the definition of the closure, but analyzed one of the semantic problems implementing the closure.

It is troublesome to clearly understand the closure, and I have not seen any authoritative JavaScript works (for example, C ++ hasBjarne StroustrupOfC ++ programming language).So apart from reading the international standards of JavaScript languageStandard ECMA-262 specification", I can't recommend the best teaching material about "closures.

The "scope chaining" of "Mu Ji" is indeed close to the essence, but it is not comprehensive. I had to make another attempt.

The meanings of closures include the following three main concepts:

Lexical Scope and Scope Chain

Lexical Scope is not invented by javacrept, but as a part of JavaScript Functions, It is an added value in the concept of "traditional" functions.

 

The lexical scope and runtime scope of traditional functions (C, C ++, Java, C #, etc.) are the same. The lexical scope of JavaScript refersFunction Definition"Environment", rather than the runtime environment of the function.

For a specific function, its "free variable" is the function.What needs to be captured in the closureMain content.Free variables (variables not defined in this function)The lexical capture (capture) Order of is (that is, the scope chaining order ):

 

A. local variable of the primary function

B. input argument of the primary function

C. Repeat A and B in the primary function until the top-level (GLOBAL scope)

 

In the followingMyObjDefinition:

Var x = 1000;// Line 0

Function MyObj(X, y ){//Line1

 

This. func1 = function (){//Line2

X ++;

Y --;

}

This. get1 = function ()

{

Return x;

}

This. get2 = function ()

{

Return y;

}

Var x = 0 ;//Line 3

}

MyObj.Prototype.AddTwo= Function (z)

{

Return this. get1 () + this. get2 () + z;

}

Var m1 = newMyObj(10, 20 );//Line 4

Var m2 = newMyObj(30, 70 );//Line 5

Console. log ('m1. x: '+ m1.get1 ());//Line 6

Console. log ('m1. y: '+ m1.get2 ());//Line 7

Console. log ('m2. x: '+ m2.get1 ());//Line 8

Console. log ('m2. y: '+ m2.get2 ());//Line 9

 

For the above example, if it is not lexical scope,Line6 ~Line9 print 10, 20, 30, 70.

However, because lexical scope captures the order, x is 0 (seeLine3), so the printing is: 0, 20, 0, 70.

Comment out line3 and print 10, 20, 30, and 70 according to the capture order.

SetMyObj(X, y)ChangeMyObj(Z, y),The printed values are 1000, 20,100, 0, and 70. Among them, 1000 is from the global (Line0) captured.

Lexical capture is performed in the parsing stage.

The above capture sequence must be performed in the parsing phase of the function. In the data structure of the function, after parsing, all "reference for capturing variables" is included, and the running phase will not change. That's why the aboveLine3. The defined rule takes precedence overInput Parameter x. Capture for execution, Line3. After the function is defined, the capture is the input parameter x.

C, C ++ and other compilation languages are directly translated into native functions, and all function running information is dynamically obtained by stack frame. The only concept that is close to closure is "global variable )". these global variables are also converted into memory addresses during compilation, and can be "solved locally" during runtime without an independent closure. These functions are not objects and do not need to be dynamically generated. Therefore, they do not need a "static" closure.

JavaScript requires an independent closure because all JavaScript is an object and can be "dynamically generated", but the definition (the first parsing) is static, the "static" part requires closure. The dynamic part is the same as the traditional function and is supported by the runtime context.

This "implementation complexity" is for the convenience of closure and the cost of processing asynchronous events.

Lexical capture is reference, not value

This is what I want to emphasize in my previous blog. If the above myObj is executed, if the value of x is captured, then the three functionsFunc1,Get1,Get2There will be no contact.

 

Because x's reference is captured, the preceding three functions see x as the same variable.

 

This is important becauseLocal Not all variablesHeap. MinimumGOOGLE V2No. But aboveLine3XMust be inHeap"Birth and Life", otherwiseFunc1,Get1,Get2The stack variable is destroyed.XIt makes the above program meaningless.

 

That is to say, the closure'sRuntimeThe cost is to extract the closed variable fromStackTransferHeap.

Summary

In my opinion, only by understanding the three concepts of appeal of closures can we be undefeated in the application of closures.

 

Seattle

 

 

 

 

 

 

 

 

 

 

 




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.