Drill down into JavaScript functions, recursion and closures (execution environment, variable object and scope chain) using the basics

Source: Internet
Author: User
Tags anonymous closure garbage collection

function expression

1. There are 2-clock methods for defining functions in JavaScript:

  1-1. function declaration:

Copy Code code as follows:

function FuncName (ARG1,ARG2,ARG3) {
function body
}

①name property: Can read the function name. Non-standard, browser support: FF, Chrome, Safari, Opera.
② function declaration Elevation: a function declaration is read before the code is executed. That is, a function call can be placed before a function declaration.

  1-2. Function expression:

Copy Code code as follows:

var funcName = function (ARG1,ARG2,ARG3) {
function body
};

① anonymous function (anonymous function, or lambda functions): No identifier after the function keyword, and the Name property value is an empty string. Anonymous functions are available when using a function as a value.
② Like other expressions, function expressions need to be assigned before they are used, so there is no "function declaration elevation" effect.
Invalid function syntax in ③ecmascript:
Copy Code code as follows:

Duplicate function declarations in if judgments

if (condition) {
function Sayhi () {
Alert ("hi!");
}
} else {
function Sayhi () {
Alert ("yo!");
}
}


Browser JavaScript engine fixes error differences: Most browsers return a second declaration, ignoring CONDITION;FF returns the first declaration when condition is true.
Use function expressions to resolve and implement:
Copy Code code as follows:

Expression of If judgment function

var Sayhi;
if (condition) {
Sayhi = function () {
Alert ("hi!");
}
} else {
Sayhi = function () {
Alert ("yo!");
}
}


2, recursive
Recursive functions are made by calling themselves in a function by name.
Copy Code code as follows:

function factorial (num) {//a classic recursive factorial functions
if (num <= 1) {
return 1;
} else {
return num * factorial (num-1);
}
}

① If the function is called using the following code, an error occurs:
Copy Code code as follows:

var anotherfactorial = factorial;
factorial = null;
Alert (Anotherfactorial (4));

After the factorial () function is saved in the variable anotherfactorial, the factorial variable is set to null and the function is no longer referenced, and the factorial () function is executed in anotherfactorial (4), and an error occurs.
Use Argument.callee (a pointer to the function being executed) to resolve:
Copy Code code 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 a non strict mode, when using recursive functions, using Argument.callee instead of function name is more insurance
In strict mode, using Argument.callee can be an error, and function expressions can be used instead of function declarations:
Copy Code code as follows:

function expressions instead of function declarations

var factorial = function f (num) {
if (num <= 1) {
return 1;
} else {
Return num * f (num-1);
}
}


4. Closure Package

A function that has access to a variable in another function scope. (Common form is function nesting)

Copy Code code 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;
};
}
}

Return anonymous function, the scope chain of the anonymous function is initialized to the active object and the global variable object that contains the function. That is, the anonymous function contains the scope of the Wai () function.
When each function is invoked, an execution environment, a variable object, and the appropriate scope chain are created.

4-1. Implementation environment and scope

The execution environment execution context, defines the other data that variables and functions have access to, and determines their respective behavior.
① Each execution environment has a variable object variable objects, saving all the variables and functions defined by the environment. The object cannot encode access, but the parser uses it in the background when it processes data.
A global variable object is the outermost execution environment. is considered a window object in a Web browser, all global objects and functions are created by properties and methods of the Window object.
After the execution of the code in the execution environment, the environment is destroyed, and the variables and function definitions stored therein are destroyed.

② code executes in the environment, a scope chain scope chain is created for variable objects to ensure orderly access to all variables and functions that are authorized to access the execution environment.
The front end of the scope chain is always the variable object of the environment in which the currently executing code resides. When the environment is a function, the active object is treated as a variable object.
The active object initially contains only one variable, that is, the Argumnt object.
The next variable object in the scope chain comes from the containing environment, and the next variable object is from the next containing environment until it is extended to the global execution environment.

③ Identifier Resolution: The process of searching for identifiers at the first level along the scope chain, starting with the preceding paragraph. "Not found usually causes an error to occur"

4-2. When the function is created and executed:

Copy Code code 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 ① creates a function compare (), it creates a scope chain that contains the global variable object beforehand and is saved in the internal [[scope]] attribute.
A variable object that ② the local function compare () and exists only in the course of the function execution.
When the function is tuned, an execution environment is created and the scope chain of the execution environment is constructed by copying the object in the [[scope]] property of the function.
③ The first time a function is invoked, such as compare (), an active object containing this, argument, Val1, and Val2 is created.
Variable objects that ④ the global execution environment (including this, result, compare) are in the second place in the scope chain of the Compare () execution environment.
The essence of the ⑤ scope chain is a list of pointers to variable objects, referencing but not actually containing variable objects.
⑥ whenever you access a variable in a function, you search for a variable with the corresponding name in the scope chain.

4-3. Scope chain of closures

A function defined inside another function adds the active object containing the function to its scope chain.
① the function object to null is equal to notifying the garbage collection routine of clearing it, and as the function scope chain is destroyed, its scope chain (not excluding the global scope) is also safely destroyed.
② because closures carry scopes that contain functions, they consume more memory than other functions.

4-4. Closures and variables

A side effect of the scope chain: Closures can only take the last value of any variable in the function.

Copy Code code as follows:

function Createfunctions () {
var result = new Array ();
for (Var i=0 i < i++) {
Result[i] = function () {
return i;
};
}
return result;
}

①createfunctions () function, assigns 10 closures to array result, and returns an array of result. Each closure returns its own index, but it actually returns 10.
Because the active object of the Createfunctions () function is kept in the scope chain of each function (closure), they refer to the same variable I, and I in the closure is 10 when the Createfunctions function is finished with the value 10.
② workaround, do not use closures, create an anonymous function, assign the I value to its parameters:
Copy Code code as follows:

function Createfunctions () {
var result = new Array ();
for (Var i=0 i < i++) {
Result[i] = function (num) {
return function () {
return num;
};
} (i);
}
return result;
}

Create an anonymous function that executes once per loop: The I value of the enclosing function in each loop is used as an argument and stored in an anonymous function. Because function arguments are passed by value, not references, the NUM value in each anonymous function is a copy of the I value for each of these loops.

4-5.this objects

The This object is bound at run time based on the execution environment of the function.
In the global function, this equals window, and this is the object when the function is called by an object.
The execution environment for an anonymous function is global, and the This object usually refers to window. This points to the object when the function execution environment is changed by call () or spply ().
① Each function is invoked, it automatically obtains two special variables: this and argument. When the intrinsic function searches for these two variables, it will never be possible to access the two variables of the external function until the expired active object is searched.
However, the this object of the external scope is kept in a variable that can be accessed by a closed package, and the closure can be accessed by the closures.

Copy Code code as follows:

The This object that the closure accesses the external function

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 that encloses the function can also be accessed by the closure by this method.

5, function declaration converted to function expression

JavaScript will function keyword the start of the declaration of functions last night, but the function declaration can not be followed by parentheses, so function () {...} (); There will be an error.
To convert a function declaration to a function expression, you add a pair of parentheses to the function declaration:

Copy Code code as follows:

(function () {
Block-level scopes
})();

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.