Explanation of Javascript_13 _ execution model

Source: Internet
Author: User

Function execution environment
Simple code:
Copy codeThe Code is as follows:
Function say (msg, other ){
Var str = "nobody say :";
This. name = 'dummies ';
Function method () {}; // var method = function (){};
Alert (str + msg );
}
Say ('Hello World ');
Alert (name); // dummies motto

When you call the say method, the first step is to create its execution environment. During the creation of the execution environment, a series of operations are completed in the defined sequence:
1. First, an 'Activity object' (Activation Object) will be created ). The activity object is another mechanism specified in the specification. An object is called an object because it has an accessible naming attribute, but it does not have a prototype (at least no predefined prototype) as a normal object ), in addition, the active object cannot be directly referenced through JavaScript code.
2. the next step for creating an execution environment for function calls is to create an arguments object, which is an object similar to an array, it stores the parameters passed when calling a function one-to-one correspondence with array members indexed by integers. This object also has the length and callee attributes (for more information, see Understanding Javascript_14 _ function form parameters and arguments). Then, an attribute named "arguments" is created for the activity object, which references the previously created arguments object.
3. Then, assign a scope for the execution environment. The scope is composed of object lists (chains. (More complex, see: Understanding Javascript_15 _ Scope allocation and variable access rules, and then sending a closure)
4. Then, the 'variable Instatiation 'process is completed by the so-called 'active object' in ECMA 262. In this case, the form parameters of the function are created as variable object naming attributes. If the parameters passed during function calling are the same as those of the form parameters, the value of the corresponding parameter is assigned to these naming attributes (otherwise, the undefined value is assigned to the naming attribute ). For a defined internal function, an attribute with the same name is created for the variable object when it is declared, and the corresponding internal function is created as a function object and specified to this attribute. The last step of variable instantiation is to create all the local variables declared in the function as variable object naming attributes. Note: In this process, except for the actual parameter values and function definitions, all other values are pre-parsed as undefined values.
5. Finally, assign a value for using the this keyword. (This points to a global object, that is, window)

After the execution environment is created, go to step 2: execute code from top to bottom in the function body.
1. when var str = 'Nobody expression' is executed, it is called 'calculate value assignment expression'. At this time, the value of key as str in the activity object is set from undefined to 'Nobody say :'.
2. When this. name = 'dummies 'is executed, the attribute name will be added to the object as this and assigned as 'dummies '.
3. Then execute function innerMethod () {}; finally execute 'alert (str + msg), and output 'Nobody say: hello world '.

Difference between function method () {} and var method = function () {}
Simple code:
Copy codeThe Code is as follows:
Function say (){
Method01 (); // method01
Method02 (); // error
Function method01 (){
Alert ('method01 ');
}
Var method02 = function (){
Alert ('method02 ');
}
}
Say ();

Why does the call method method01 run normally while the call method method02 reports an error?
First, you must clearly know that method01 is a function object, while method02 is a variable that points to another function object. According to the content in the previous section, during the 'variable Instatiation 'process completed by the 'active object', The method01 function is 'pre-resolution' normally ', when the variable method02 is parsed as the undefined value, when it comes to the code execution stage, because the call of method02 is used as a method before its function expression is computed, an error is inevitable. The solution is simple, that is, convert var method02 = function (){...} before calling its method02 (), you can define the function (function method () {...}) by using the function declaration method (){...}).
Note: The computed function expression means that the program runs to var method02 = function (){...}. Method02 points to a function object. Because in 'pre-resolution', method02 is assigned only to undefined.

Global execution environment (as mentioned in execution model analysis, it is no longer necessary)
On a page, a global execution environment is created when JS Code is loaded for the first time. The scope chain of the global execution environment is actually composed of only one object, that is, the global object (window ), before executing JavaScript code, the engine creates the Scope Chain structure. The global execution environment also involves variable instantiation. Its internal functions are standard top-level function declarations involving most JavaScript code. In addition, global objects are variable objects during variable instantiation, Which is why global declared functions are attributes of global objects. Similarly, variables declared globally use this object to reference global objects in the global execution environment.

Note: The difference between the Activation Object in the 'function execution environment' and the Variable Object in the global execution environment, Variable Object is also called the Activation Object (because of some differences, therefore, a new name is used in the specification to show the difference. The Global execution environment/Eval execution environment is called Variable Object, and the function execution environment is called Activation Object ).

Eval execution environment
Variable Object is a Variable Object in the current execution context when Eval is called ). The eval function is called in the global execution environment. Its Variable Object is a global Object, and its Variable Object is called in the function) is the activity Object of the function ).
Copy codeThe Code is as follows:
// Passed in FF2.0, IE7, Opera9.25, Safari3.0.4
Function fn (arg ){
Var innerVar = "variable in function ";
Eval ('\
Var evalVar = "variable in eval ";\
Document. write (arg + "<br/> ");\
Document. write (innerVar + "<br/> ");\
');
Document. write (evalVar );
}
Fn ("arguments for function ");

The output result is:
Arguments for function
Variable in function
Variable in eval
Note: In eval calls, you can access the fn parameters and local variables of the function. The local variables defined in eval can also be accessed in fn, because their Varible objects are the same Object.
When you enter the Eval Code execution, a new Scope Chain will be created, with the same content as the Scope Chain of the current execution context.

Last Instance
The Code is as follows:
Copy codeThe Code is as follows:
Var outerVar1 = "variable in global code ";
Function fn1 (arg1, arg2 ){
Var innerVar1 = "variable in function code ";
Function fn2 () {return outerVar1 + "-" + innerVar1 + "-" + "-" + (arg1 + arg2 );}
Return fn2 ();
}
Var outerVar2 = fn1 (10, 20 );

The execution process is roughly as follows:
1. initialize the Global Object, that is, the window Object, and the Variable Object is the window Object itself. Create a Scope Chain object, which is assumed to be scope_1 and only contains the window object.
2. Scan the JS source code (read the source code and may have a lexical syntax analysis process) and get the defined variable name and function object from the result. Scan order:
2.1 The variable outerVar1 is found. Add the outerVar1 attribute to the window object and the value is undefined;
2.2 The fn1 function is found. Use this definition to create a function object and pass it to the Scope Chain of the creation process as scope_1. Add the result to the window property with the name fn1 and the value as the returned function object. Note that the internal [Scope] of fn1 is scope_1. Note that the creation process does not perform special processing on the JS Code in the function body. It can be understood that the scan results of the function body JS Code are saved on the internal attributes of the function object, perform further processing during function execution. This is critical to understanding Function Code, especially Variable Instantiation in nested Function definitions;
2.3 The variable outerVar2 is found. Add the outerVar2 attribute to the window object and the value is undefined;
3. Execute the outerVar1 value assignment statement and assign the value to "variable in global code ".
4. Execute the fn1 function to obtain the returned value:
4.1 create an Activation Object, for example activation_1; create a new Scope Chain, for example, scope_2, and activation_1 is the first Object in scope_2, the second object is the window object (from [[Scope] of fn1, that is, the content in scope_1 );
4.2 list of processing parameters. Set the arg1 and arg2 attributes on activation_1 with values of 10 and 20, respectively. Create an arguments object and set it. Set arguments to the property of activation_1;
4.3 perform a process similar to step 2 on the fn1 function body:
4.3.1 The innerVar1 variable is found. The innerVar1 attribute is added to the activation_1 object and the value is undefine;
4.3.2 The definition of function fn2 is found. Use this definition to create a function object and pass it to the Scope Chain of the creation process as scope_2 (the Scope Chain of function fn1 is the content of the current execution context ). Add the result to the activation_1 attribute. The value is fn2 and the returned function object. Note that the internal [Scope] of fn2 is scope_2;
4.4 execute the value assignment statement innerVar1 and assign the value to "variable in function code ".
4.5 run fn2:
4.5.1 create an Activation Object, assuming activation_2; create a new Scope Chain, assuming scope_3, and the first Object in scope_3 is activation_2, the following objects are activation_1 and window objects ([Scope] From fn2, that is, scope_2 );
4.5.2 list of processing parameters. Because fn2 has no parameters, you only need to create an arguments object and set it to the attribute of activation_2.
4.5.3 perform a process similar to step 2 on the fn2 function body, and no variable definition or function declaration is found.
4.5.4 execute the function body. Reference any variable and search from scope_3. In this example, outerVar1 will be found on the window; innerVar1, arg1, and arg2 will be found on activation_1.
4.5.5 discard scope_3 and activation_2, which can be recycled by garbage collection ).
4.5.6 return the return value of fn2.
4.6 activation_1 and scope_2 are discarded.
4.7 return results.
5. Assign the result to outerVar2.

Refer:
Http://www.cnblogs.com/RicCC/archive/2008/02/15/JavaScript-Object-Model-Execution-Model.html
Http://www.cn-cuckoo.com/2007/08/01/understand-javascript-closures-72.html

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.