Understanding javascript_13_ Execution Model _javascript skills

Source: Internet
Author: User
Tags eval function definition
Function Execution Environment
Simple code:
Copy Code code as follows:

function Say (Msg,other) {
var str = "Nobody say:";
THIS.name = ' idiot's motto ';
Function method () {};//var method = function () {};
alert (str+msg);
}
Say (' Hello World ');
alert (name);/Fool's motto

When you call the Say method, the first step is to create its execution environment, and in the process of creating the execution environment, you will complete a series of actions in the order defined:
1. An ' active object ' (activation) is created first. The activity object is another mechanism stipulated in the specification. It is called an object because it has a named property that is accessible, but it is not as prototype as a normal object (at least without a predefined prototype) and cannot be referenced directly by JavaScript code.
2. The next step in creating an execution environment for a function call is to create a arguments object, an array-like object that preserves the parameters passed by the calling function as an array member of an integer index. This object also has the length and callee attributes (more in depth, see Understanding javascript_14_ function form parameters and arguments). Then, a property named "Arguments" is created for the active object that references the arguments object that was created earlier.
3. Next, assign scopes to the execution environment. The scope consists of an object list (chain). (more complex, see: Understanding the Javascript_15_ scope assignment and variable access rules, and then send a closure)
4. The process of ' variable instantiation ' (Variable instatiation), which is called ' active object ' completed in ECMA 262, will then occur. The form parameter of the function is created as a named property of the Mutable object, and if the arguments passed when the function is called are consistent with the formal arguments, the value of the corresponding parameter is assigned to the named property (otherwise, the named property is assigned a undefined value). For a defined intrinsic function, a property of the same name is created for the Mutable object with the name it declares, and the corresponding intrinsic function is created as a function object and assigned to the property. The final step in the variable instantiation is to create the named attribute of all local variables declared within the function as mutable objects. Note: In this process, in addition to the actual parameters have value and function definition, the other is ' undefined ' for the value of the.
5. Finally, you want to assign a value to use the This keyword. (This now points to a global object, that is, window)

After the execution of the environment has been created, you go to step two: in the body of the function, execute the code from top to bottom.
1. When execution to the Var str= ' Nobody say ' occurs the process called ' Evaluating an Assignment expression ', the value of the key in the active object, str, is set from undefined to ' nobody say: '.
2. Execute to this.name= ' idiot's motto ', add attribute name to the object as this, and assign it as ' idiot's motto '.
3. Then execute function innermethod () {}; last executed ' alert (str+msg), Output ' Nobody Say:hello world '.

Difference between function method () {} and var method = function () {}
Simple code:
Copy Code code as follows:

function say () {
METHOD01 ();//method01
METHOD02 ();//error
function Method01 () {
Alert (' method01 ');
}
var method02 = function () {
Alert (' method02 ');
}
}
Say ();

Why call Method method01 can run normally, and call method Method02 will error?
First, you have to know explicitly that METHOD01 is a function object, and METHOD02 is a variable that points to another function object. According to the contents of the previous section, in the process of ' variable instantiation ' (Variable instatiation) of the ' active object ', a normal ' pre resolution ' is performed on the function method01, and for a variable method02 resolves to a undefined value, When entering into the process of executing code, because the METHOD02 call is used before it evaluates the function expression, the undefined as a method is bound to be an error. The solution is relatively simple, that is, the Var method02=function () {...} The function (function method () {...}) can be defined before the call to its method02 () or by function declaration.
Note: The calculation function expression means that the program executes to the var method02 = function () {...}. Method02 really points to a function object at this point. Because in ' pre-resolution ', METHOD02 was only assigned to undefined.

Global Execution Environment ("Analysis of Executive model" has been said, no longer in-depth)
In a page, the first time you load the JS code to create a global execution environment, the scope of the global execution environment chain is actually only an object, that is, the Global Object (window), before beginning the execution of JavaScript code, the engine will create this scope chain structure. The global execution environment also has a variable instantiation process, and its intrinsic function is the general top-level function declaration that involves most of the JavaScript code. Also, global objects are mutable objects during variable instantiation, which is why globally declared functions are the cause of global object properties. The variables for global declarations are the same. The global execution environment uses the This object to refer to the global object.

Note: Distinguish between the active object (Activation object) in the ' Function execution Environment ' and the Mutable object (Vriable object) in the global execution environment, Variable object is also called Activation object (because there are some differences, So the specification of a new name in order to differentiate, the global Execution Environment/eval execution Environment called variable object, function execution environment is called activation object.

Eval Execution Environment
The Mutable object (Variable object) when the eval execution environment is built is the Mutable object (Variable objects) in the current execution context when the eval is invoked. The Eval function is invoked in a global execution environment, and its Mutable object (Variable object) is a global object, and in a function it invokes Eval, and its Mutable object (Variable object) is the active object (activation object) of the function.
Copy Code code 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 results are:
Arguments for function
Variable in function
Variable in eval
Description: Parameters, local variables that can access the FN in the eval call, and local variables defined in eval can also be accessed in the function FN, because their varible object is the same.
Entering eval code execution creates a new scope Chain that is exactly the same as the scope Chain of the current execution context.

the final example
The code is as follows:
Copy Code code 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 generally as follows:
1. Initializes the global object, which is the Window object, and Variable object to itself. Creates a scope chain object, assuming Scope_1, which contains only the Window object.
2. Scan JS source code (read into the source code, may have lexical parsing process), from the results can be defined variable name, function object. In the order of scanning:
2.1 Find the variable outerVar1, add the OuterVar1 property on the Window object, the value is undefined;
2.2 Discover the definition of function fn1, use this definition to create function objects, pass to the scope chain of the creation process as scope_1. Add the result to the window's properties, the name is FN1, and the value is the returned function object. Note that fn1 's internal [[Scope]] is scope_1. In addition, note that the creation process will not be in the function of the JS code to do special processing, you can understand that only the function of the JS code scan results stored in the function object's internal properties, in the function of the execution of further processing. This is critical to understanding function Code, especially variable instantiation in nested function definitions;
2.3 Find the variable outerVar2, add the OuterVar2 property on the Window object, the value is undefined;
3. Executes the OUTERVAR1 assignment statement, assigned the value of "variable in global Code".
4. Perform function fn1, get return value:
4.1 Create activation object, assume activation_1; Create a new scope Chain, assuming that the first object in Scope_2,scope_2 is Activation_1 and the second object is the Window object ( from fn1 [[[Scope]], i.e. content in scope_1;
4.2 Processing parameter list. Set properties on Activation_1 arg1, arg2, Values 10, 20, respectively. Create the arguments object and set the arguments to the Activation_1 property;
4.3 The FN1 function body performs a process similar to step 2:
4.3.1 found variable innerVar1, add innerVar1 attribute on Activation_1 object, value is undefine;
4.3.2 discovers the definition of function fn2, using this definition to create a function object that passes to the scope of the creation process chain to scope_2 (the scope of the function fn1 is the content of the current execution context). Add the result to the Activation_1 property, the name is FN2, and the value is the returned function object. Note that the internal [[Scope]] of the fn2 is scope_2;
4.4 Executes the INNERVAR1 assignment statement with the value "variable in function code".
4.5 Executive FN2:
4.5.1 creates activation object, assuming activation_2, and creates a new scope Chain, assuming that the first object in Scope_3,scope_3 is Activation_ 2, the next object is Activation_1, Window object (from Fn2 [[[Scope]], i.e. scope_2);
4.5.2 processing the parameter list. Because FN2 has no parameters, it is only used to create the arguments object and set it to the Activation_2 property.
4.5.3 performs a process similar to step 2 for the function body of fn2, and no variable definitions and function declarations are found.
4.5.4 executes the function body. For any variable reference, search from Scope_3, in this example, OUTERVAR1 will be found on window, InnerVar1, Arg1, arg2 will be found on activation_1.
4.5.5 Discard Scope_3, activation_2 (meaning they can be garbage collected).
4.5.6 returns the return value of FN2.
4.6 Discard activation_1, scope_2.
4.7 Returns the result.
5. Assign the result to OUTERVAR2.

Reference:
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

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.