JavaScript in-depth understanding of function-function transfer value

Source: Internet
Author: User
Tags sorted by name

In JavaScript, because the function name is a variable, the function can also be used as a value. Not only can we pass a function to another function like passing parameters, but we can also return a function as the return value of another function.

passing a function as a parameter

Since the function is an object, the function can be passed directly as a parameter. Take a look at the following example:

// Define a function function Say (str) {  return "Hello" +str;} // Call Function alert (Say ("JavaScript"));   // back to "Hello JavaScript"

The above code defines a function say() that receives a string parameter that returns the string "Hello argument string" after the function is called. The above function definition and invocation method is our usual practice, but this function call lacks flexibility. We can write a general function by using the function as an argument. This general function can call any function that matches a parameter.

// define a common function function Callfun (fun,arg) {  /// The first parameter is a function object  return fun (ARG)           ;}

The Callfun () function above is a general function whose first argument is a function object, and its return value is the result of the execution of the function in the parameter. Use this generic function to execute the previously defined say() function as follows:

Callfun (say, "JavaScript"); // back to "Hello JavaScript"

As you can see, no matter what the function, as long as it has only one argument, then you can use callFun() the function to make the call.

function as return value

The more magical part of JavaScript functions is the ability to return a function as the return value of another function. The greatest benefit to us is that the parameter scope of the intrinsic function is extended. Take a look at the following example:

function fn1 (Arg) {  varfunction(num) {    return arg + num;  }   // a Function Object  is returned at this time return rel;}        

fn1()Another function is defined in the above function rel() , and rel() The return value of the function is the result of fn1() rel() adding the arguments to the function and the parameters of the function. Finally, the fn1() function returns the whole rel as a result. We can call this function as follows:

var f = fn1, alert (                              The scope of the F (//arg) is enlarged

As you can see, the assignment of an intrinsic function is done in the rel last function, and the call to the function is now complete, which is supposed to be f() fn1() f = fn1(20) recycled as 20 of the parameters after the operation is completed, but because the fn1() inside rel of the function Returned as a return value, allowing the scope of the fn1() function's arguments arg to be extended.

The benefit of returning a function as a result is that we can determine the parameters of the intrinsic function when the function is executed, which gives a great deal of flexibility to the invocation of the function.

Let's take a sort of example to illustrate the use of functions as parameters and as return values.

In introducing the array object, we have said that the array object has a method that is used to sort the arrays of sort() elements. Look at the following example:

var arr = [1,2,215,16,58,35,8// for JavaScript, the default is to     sort by string

Because for JavaScript, the default is to sort by string, so the return result we get is: [1, 16, 2, 215, 35, 58, 8] .

If we need to sort by the size of a number, sort() there is an optional parameter in the method sortOrder . This parameter determines the sort order, the sortOrder name of the sort function, and the function has 2 parameters and requires an integer value to be returned. If a value greater than 0 is returned, the first argument is greater than the second parameter, and if a value equal to 0 is returned, then two parameters are equal, and if a value less than 0 is returned, then the first argument is less than the second argument. Now let's write the sortOrder method.

// methods for sorting by numeric size function SortOrder (A, a  ) {return A-b;}                

The sorting function above has 2 parameters A and B, and the return value conforms to the ordering requirement. Here we use this sort function to reorder the array arr.

// Reorder Console.info (Arr.sort (SortOrder)) with a custom sort method ;                              

The results are as follows:

Now we have the correct result for sorting by numerical size. sort()a custom ordering of methods is the best example of using a function as a parameter to pass.

Let's look at the sorting of objects. Look at the following example:

function Person (name,age) {  this. Name = name;    this. Age = Age ;} var New Person ("John", at all); var New Person ("Tom", +); var New Person ("Jack",); var pArr = [P1,P2,P3];    

The above code creates an Person object type and Person instantiates 3 objects by type, giving them different name and age attributes respectively. And put them in an array, ready to sort.

Next we'll customize two sorting methods, sorted by name and age, respectively.

//Sort by namefunctionSortbyname (obj1,obj2) {if(Obj1.name >obj2.name) {return1; }Else if(Obj1.name = =obj2.name) {return0; }Else {    return-1; }}//Sort by agefunctionSortbyage (obj1,obj2) {returnObj1.age-Obj2.age;} 

By passing the 2 sort functions defined above as parameters into the sort() method, we can get the desired result.

// Sort by name Parr.sort (sortbyname); // Output Results  for (var i = 0; i < parr.length; i++) {  + "," + parr[i].age);}       

The results, sorted by name, are as follows:

// Sort by age Parr.sort (sortbyage); // Output Results  for (var i = 0; i < parr.length; i++) {  + "," + parr[i].age);}          

The results sorted by age are as follows:

The above approach can be used to sort objects by attribute, but if we have 100 properties in our object and now require a different sort for each attribute, is it not that we want to write 100 different sorting methods? The answer is no, we can solve this problem perfectly by returning the sort function as the return value of the function, and then passing in the sorted property when the sort is executed. Look at the following code:

//general functions for sorting by object propertiesfunctionSortbyproperty (PropertyName) {varSortfun =function(obj1,obj2) {if(Obj1[propertyname] >Obj2[propertyname]) {      return1; }Else if(Obj1[propertyname] = =Obj2[propertyname]) {      return0; }Else{return-1;} }  returnSortfun;} 

We can call this sort function as follows:

// Sort by name Parr.sort (sortbyproperty ("name")); // Parr.sort (Sortbyproperty ("Age") in chronological order ;                             

In some advanced JavaScript frameworks (such as jquery), where functions are used as parameters to pass, and functions are used as return values for another function, it is important to understand the function-passing mechanism of JavaScript in order to read these frameworks.

This article copyright belongs to the House of jquery, reprint please indicate source: http://www.htmleaf.com/ziliaoku/qianduanjiaocheng/201512092886.html

JavaScript in-depth understanding of function-function transfer value

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.