JavaScript advanced programming (version 3rd) learning notes 9js functions (below) _ basic knowledge-js tutorial

Source: Internet
Author: User
A function is an object that has all the features of a general object. In addition to its own attributes and methods, it can also be used as a reference type value, in fact, in the previous example, we have already used a function as the value of an object property. For example, a function can also be used as a parameter or return value of another function, the callback function in asynchronous processing is a typical usage and then we look at the function-an object with magical colors.

9. functions as values

In a general programming language, if you want to use a function as a value, you must use a method similar to a function pointer or proxy. However, in ECMAScript, a function is an object, has all the features of a general object. In addition to functions, they can have their own attributes and methods. They can also be used as a reference type value, in fact, in the previous example, we have already used a function as the value of an object property. For example, a function can also be used as a parameter or return value of another function, the callback function in asynchronous processing is a typical usage.

The Code is as follows:


Var name = 'linjisong ';
Var person = {name: 'external '};
Function getName (){
Return this. name;
}
Function sum (){
Var total = 0,
L = arguments. length;
For (; l --)
{
Total + = arguments L-1 1];
}
Return total;
}

// Define the function that calls the function, using the function as the form parameter
Function callFn (fn, arguments, scope ){
Arguments = arguments | [];
Scope = scope | window;
Return fn. apply (scope, arguments );
}
// Call callFn and use the function as the actual Parameter
Console.info (callFn (getName); // linjisong
Console.info (callFn (getName, '', person); // oulinhai
Console.info (callFn (sum, [1, 2, 3, 4]); // 10


Let's look at a typical example of using a function as the return value. This example is from Chapter 5th of the original book:

The Code is as follows:


Function createComparisonFunction (propertyName ){
Return function (object1, object2 ){
Var value1 = object1 [propertyName];
Var value2 = object2 [propertyName];

If (value1 <value2 ){
Return-1;
} Else if (value1> value2 ){
Return 1;
} Else {
Return 0;
}
};
}

Var data = [{name: "Zachary", age: 28 },{ name: "Nicolas", age: 29}];

Data. sort (createComparisonFunction ("name "));
Console.info (data [0]. name); // Nicolas

Data. sort (createComparisonFunction ("age "));
Console.info (data [0]. name); // Zachary



10. Closure)

A closure is a function that has the right to access variables in another function scope. Objects are data with functions, while closures are functions with data.

First, closure is a function, and then closure is a function with data. So what data does it contain? Let's look up the example of a function as the return value. An anonymous function is returned. As this anonymous function is returned, the code of the createComparisonFunction () function on the outer layer is executed. According to the preceding conclusion, the execution environment of the outer function will pop up and destroy the stack. However, in the subsequent sorting, we can see that the returned anonymous function can still access the propertyName in the scope of createComparisonFunction, this indicates that although the execution environment corresponding to createComparisonFunction () has been destroyed, the activity objects corresponding to the execution environment have not been destroyed, instead, it serves as an object in the scope chain of the returned anonymous function. In other words, the data contained in the closure of the returned anonymous function is the corresponding activity object of the outer function. Because the attributes of the activity object (that is, the variables, functions, and form parameters defined in the outer function) change with the code execution of the outer function, therefore, the closure composed of anonymous functions that are finally returned contains data that is the activity object after the code of the outer function is executed, that is, the final state.

I hope to understand the above paragraph and try again and again. Although I have tried my best to describe more easily, the concept of closure is still somewhat abstract. Here is an example. This example is from Chapter 7th of the original book:

The Code is as follows:


Function createFunctions (){
Var result = new Array ();
For (var I = 0; I <10; I ++ ){
Result [I] = function (){
Return I;
};
}
Return result;
}

Var funcs = createFunctions ();
For (var I = 0, l = funcs. length; I <l; I ++ ){
Console.info (funcs [I] (); // each function outputs 10
}


Here, because the data contained in the closure is the final state of the createFunctions corresponding activity object, after the createFunctions () code is executed, the property I of the activity object has changed to 10, therefore, every function returned in the following call outputs 10. To solve this problem, you can use the anonymous function scope to save the status:

The 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;
}


Each status is saved using an anonymous function that is called immediately (stored in the active object corresponding to the anonymous function), and when the final returned function is called, you can use the data contained in the closure (the data in the corresponding anonymous function activity object) to access the data correctly. The output result is 0, 1 ,... 9. Of course, in this way, 10 closures are created, which has a great impact on the performance. Therefore, we recommend that you do not abuse closures. In addition, since the closure will save the activity objects of other execution environments as a part of its own scope chain, this may also cause memory leakage. Although the closure has potential efficiency and memory risks, the closure function is too powerful. Let's take a look at the closure application-First let's go back to the function binding method bind () mentioned yesterday ().

(1) function binding and currying)

A. Let's look at this again. Let's look at an example (chapter 1 of the original book ):

The Code is as follows:


Hello

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.