In-depth usage of Javascript Functions, recursion, and closures (execution environment, variable object, and scope chain)

Source: Internet
Author: User

Function expression

1. A function defined in JavaScript can be used for two minutes:

  1-1. function declaration:
Copy codeThe Code is as follows:
Function funcName (arg1, arg2, arg3 ){
// Function body
}

① Name attribute: the name of the function to be read. Non-standard. browsers support: FF, Chrome, safari, and Opera.
② Function declaration escalation: The function declaration is read before the code is executed. That is, the function call can be placed before the function declaration.

  1-2. function expression:
Copy codeThe Code is as follows:
Var funcName = function (arg1, arg2, arg3 ){
// Function body
};

① Anonymous function (anonymous function, or Lambda function): There is no identifier after the function keyword, and the name attribute value is an empty string. You can use anonymous functions when using functions as values.
② Similar to other expressions, the function expression must be assigned a value before it is used, so the function declaration is not promoted.
③ Invalid function syntax in ECMAScript:
Copy codeThe Code is as follows:
Repeated function declaration in if judgment

If (condition ){
Function sayHi (){
Alert ("Hi! ");
}
} Else {
Function sayHi (){
Alert ("Yo! ");
}
}

Differences in browser JavaScript Engine correction errors: Most browsers return the second declaration, ignoring condition; FF returns the first declaration when condition is true.
Function expressions can be used to resolve and implement:
Copy codeThe Code is as follows:
If function expression

Var sayHi;
If (condition ){
SayHi = function (){
Alert ("Hi! ");
}
} Else {
SayHi = function (){
Alert ("Yo! ");
}
}

2. Recursion
A recursive function is a function that calls itself by name.
Copy codeThe Code is as follows:
Function factorial (num) {// a classic recursive factorial function
If (num <= 1 ){
Return 1;
} Else {
Return num * factorial (num-1 );
}
}

① If you use the following code to call this function, an error occurs:
Copy codeThe Code is as follows:
Var anotherFactorial = factorial;
Factorial = null;
Alert (anotherFactorial (4 ));

After the factorial () function is saved to the variable anotherFactorial, if the factorial variable is set to null, the function is no longer referenced. However, factorial () is executed in anotherFactorial (4), so an error occurs.
Use argument. callee (pointer to the function being executed) to solve:
Copy codeThe Code is as follows:
Solution

Function factorial (num ){
If (num <= 1 ){
Return 1;
} Else {
Return num * arguments. callee (num-1 );
}
}

Var anotherFactorial = factorial;
Factorial = null;
Alert (anotherFactorial (4); // 24

In non-strict mode, when recursive functions are used, it is safer to use argument. callee instead of function names.
In strict mode, an error occurs when argument. callee is used. The function declaration can be replaced by a function expression:
Copy codeThe Code is as follows:
Function expressions replace function declaration

Var factorial = function f (num ){
If (num <= 1 ){
Return 1;
} Else {
Return num * f (num-1 );
}
}

4. Closure

A function that has the right to access variables in another function scope. (Common form: function nesting)
Copy codeThe Code is as follows:
Function wai (pro ){
Return function (obj1, obj2 ){
Var val1 = obj1 [pro];
Var val2 = obj2 [pro];
If (val1 <val2 ){
Return-1;
} Else if (val1> val2 ){
Return 1;
} Else {
Return 0;
};
}
}

When return is an anonymous function, the scope chain of the anonymous function is initialized to the activity object and global variable object that contains the function. That is, an anonymous function contains the scope of the wai () function.
When a function is called, an execution environment, a variable object, and the corresponding scope chain are created.

4-1. Execution Environment and scope

The execution environment execution context is short for the environment. It defines other data that variables and functions have the right to access and determines their respective actions.
① Each execution environment has a variable object, which stores all variables and functions defined by the environment. This object cannot be accessed by encoding, but the parser will use it in the background when processing data.
The global variable object is the execution environment at the periphery. It is considered as a window object in a Web browser. Therefore, all global objects and functions are created by properties and methods of window objects.
After the code in the execution environment is executed, the environment is destroyed, and the variables and function definitions in the environment are also destroyed.

② When the code is executed in the environment, a scope chain of the variable object will be created to ensure orderly access to all variables and functions that the execution environment has the right to access.
The frontend of the scope chain is always the variable object in the environment where the code is currently executed. When the environment is a function, the activity object is used as the variable object.
The activity object contains only one variable, that is, the argumnt object.
The next variable object in the scope chain comes from the inclusion environment, and the next variable object comes from the next inclusion environment until it continues to the global execution environment.

③ Identifier resolution: the process of searching identifiers at the level of the scope chain starting from the previous section. [Errors may occur if you cannot find them]

4-2. When creating and executing a function:
Copy codeThe Code is as follows:
Function compare (val1, val2 ){
If (val1 <val2 ){
Return-1;
} Else if (val1> val2 ){
Return 1;
} Else {
Return 0;
};
}
Var result = compare (5, 10 );

① When the compare () function is created, a scope chain containing the global variable object is created and saved in the internal [scope] attribute.
② The variable object of the local function compare () exists only during function execution.
When you call a function, an execution environment is created, and the scope chain of the execution environment is constructed by copying objects in the [[scope] attribute of the function.
③ When a function is called for the first time, for example, compare (), an activity object containing this, argument, val1, and val2.
④ The variable objects (including this, result, and compare) in the global execution environment are second in the scope chain of the compare () execution environment.
⑤ The scope chain is essentially a pointer list pointing to a variable object. It only references but does not actually contain the variable object.
⑥ Whenever a variable is accessed in the function, the variable with the corresponding name will be searched in the row scope chain.

4-3. Scope chain of closure

The function defined in another function adds the activity objects containing the function to its scope chain.
① Assigning a null value to a function object is equivalent to clearing the garbage collection routine. As the function scope chain is destroyed, its scope chain (excluding the global scope) will also be safely destroyed.
② Because closures carry scopes containing functions, they occupy more memory than other functions.

4-4. Closure and variables

One side effect of the scope chain: the closure can only obtain the last value of any variable in the function.
Copy codeThe Code is as follows:
Function createFunctions (){
Var result = new Array ();
For (var I = 0; I <10; I ++ ){
Result [I] = function (){
Return I;
};
}
Return result;
}

① CreateFunctions () function, assign 10 closures to the array result, and then return the result array. Each closure returns its own index, but actually returns 10.
Because the scope chain of each function (closure) stores the activity objects of the createFunctions () function, they reference the same variable I, after the createFunctions function is executed, the I value in the closure is 10.
② Solution: Create an anonymous function without using the closure and assign the I value to its parameter:
Copy codeThe Code is as follows:
Function createFunctions (){
Var result = new Array ();
For (var I = 0; I <10; I ++ ){
Result [I] = function (num ){
Return function (){
Return num;
};
} (I );
}
Return result;
}

Create an anonymous function that runs once every cycle: Save the I value of the function enclosed in each cycle as a parameter to the anonymous function. Because function parameters are passed by value instead of reference, the num value in each anonymous function is a copy of the I value for each cycle.

4-5.this object

This object is bound to the function-based execution environment during runtime.
In a global function, this is equal to window. When a function is called by an object, this is the object.
The execution environment of anonymous functions is global, and this object usually refers to window. When calling () or spply () is used to change the function execution environment, this points to its object.
① When a function is called, two special variables are automatically obtained: this and argument. When an internal function searches for these two variables, it only searches for expired activity objects and never accesses these two variables of an external function.
However, by saving this object in an external scope in a variable that can be accessed by a closure, the closure can access this object.
Copy codeThe Code is as follows:
This object for the closure to access external functions

Var name = "The Window ";

Var object = {
Name: "My Object ",

GetNameFunc: function (){
Var that = this;
Return function (){
Return that. name;
};
}
};

Alert (object. getNameFunc (); // "MyObject"

The argument object of the function can be accessed by the closure through this method.

5. convert a function declaration to a function expression

JavaScript starts the function declaration with the function keyword last night, but the function declaration cannot be followed by parentheses, so function () {...} (); will fail.
To convert a function declaration to a function expression, you must add a pair of parentheses to the function declaration:
Copy codeThe Code is as follows:
(Function (){
// Block-level scope
})();

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.