Talk about the understanding of JS closure, execution context, scope chain, active object AO, variable object vo

Source: Internet
Author: User

Intro: About Closures
What is a closure?
from a definition point of view, all functions can be closures. A closure is formed when a function invokes a variable (usually called a free variable) that is not defined within its own scope, and the closure is a combination of the code block and the data in the context in which the code block was created .


Example: function mytest () {
var test=10;
return function () {
test++;
alert (test);
      } 
}
var atest = new MyTest ();//function returned by reference
atest (); One
atest ();///
PS: Note the common error-->for (var i,len=xx.length;i<len;i++) loop using closures, when the free variable we are referencing is I, because I has not been released in memory, the function each time alert (i), The values are final I; (many examples, do not write)
by testing the results we can see that the closure causes the variable referenced by the function to remain in memory for what reason?
The simple explanation is that the returned function references the variable test, and when the browser resolves to var atest=new mytest (), this line and the Mytes () function is finished, and when the memory release is ready, it is found that the returned function references the test variable. So that the stack does not go out;
to fully figure this out, we need to further understand the problem of AO (active object) and VO (Variable object) and scope chain, execution context.
So how does this whole mechanism browser actually parse it?
no hurry, let's take a look at the execution context, scope chain, active object, and variable object;
write in the previous execution context:
A: Definition:

each time the controller goes to the ECMAScript executable code, it goes into an execution context. The execution context (-EC) is an abstraction in the ECMA-262 standard that distinguishes it from the concept of executable (executable code). The active execution context group logically composes a stack. The bottom of the stack is always the global context, and the top is the current (active) execution context. The stack is modified when the EC type enters and exits the context (either in the stack or out of the stack). B: If we define an execution context stack is an array:ecstack = [];//globalcontext always at the bottom of the stack, the remaining functioncontext are pressed in the order of activation, and are ejected at the endEcstack = [
Globalcontext
];ecstack = [functionaacontext,//function A intrinsic function a executable codefunctionacontext,//function A executable code (which does not contain intrinsic function code and can only be declared, as in the global only for function a declaration, when an intrinsic function is required to activate, create Globalcontext Execution context in order to execute the corresponding code) The call ends after the stack
];;

PS: The current execution context is pressed into the stack each time the function is entered (even if function is called recursively or as a constructor) or when the built-in Eval function is working;

 

1. Scope Chain
First, how do we create a scope, function (). The function is the only one in JavaScript that can create scopes, that is, the for, if, and while {} cannot be created out of scope. Distinguishes the block scope {} from C + +.
After the scope of a function is created, it will run through his beginning "{", "final"}, scope

stored when the function is created, surviving with the function

。 This sentence should be focused on understanding through the 2 words, if the function is nested within a number of functions, then from the most inner-layer function scope in order to form a chain of action.
PS: The variable lookup mechanism that requires us to understand the scope chain is from the inside out. Look for the scope of the first, once again outward, if not, then the same as no Var declaration (for the global Add a property);

The scope chain is the list of all variable objects (including parent variable objects) in the internal context


2. Variable objects (Variable object), active objects (Activation object)
When the browser parses the code, it first makes variable declaration and function declaration, and the function parameter declaration;
(global scope) So where are the variables of these precedence declarations stored?
Yes, it's in the variable object (abstract concept); How does an active object understand it?

abstract Variable Object VO (general behavior of the variable initialization process)
    -- Global Context Variable object Globalcontextvo
(VO = = = This = = = Global)

--Function Context Variable object Functioncontextvo
(VO = = = AO, and added <arguments> (array of formal parameters) and <formal parameters> (values of formal parameters))

PS: In the context of function execution, VO is not directly accessible, at this time by the active object Play Vo's role. The arguments object is a property of the active object, and it includes the following properties:

    1. Callee-a reference to the current function

    2. length-true number of arguments passed

    3. The value of the Properties-indexes (integer of String type) property is the parameter value of the function, arranged from left to right in the argument list. Properties-indexes the number of internal elements is equal to arguments.length. The value of properties-indexes is shared with the actual passed in parameters.

Now let's just string it up.

1. Global execution context

Create Global. VO

2. Assigning values to global variables | Call function () (activation)

When the function is activated, the current AO is obtained, with the declaration of the intrinsic function, the declaration of the internal variable, the formal parameter

3. Enter the context of the active function

Perform assignment of variables on the scope chain (scope chain contains global Vo, and AO of current execution context)

4.a, if there is an intrinsic function call (or self-executing) in the function, repeat 3;

4.B returns a function (or its reference), and the function has a reference to a free variable--form a closure--the scope chain mechanism is still valid--the functioncontext that is currently pressed into the execution context stack will not stack;--> back to 2;

4.c normal return or normal end, functioncontext out Stack;--> back to 2;

5. All the code is executed, the program shuts down, and the memory is freed.

I implore the veteran to point out the wrong and incorrect understanding of the place; Sophomore student, study hard ... Forgive me.

Pure hand, reproduced collection does not indicate the source, (estimates will not have, please ignore).

Written at the end:

If you are just beginning to touch JavaScript, if you also believe that the blog park can make your study more planning and in-depth, I recommend you to see Wang Fu Peng teacher and Uncle Tom 's blog, their own careful study, record their feelings, there will be a harvest. Come on. I am trying to see in-depth series of design patterns, it feels not very smooth, some do not understand, I hope that experienced bloggers can guide the guidance. This is my first blog post, I really hope to be able to find a mentor in the blog Park.

And put Uncle Tom in the address of the JavaScript series blog,

http://www.cnblogs.com/TomXu/archive/2011/12/15/2288411.html

Talk about the understanding of JS closure, execution context, scope chain, active object AO, variable object vo

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.