JS: Deep function (function is Object)

Source: Internet
Author: User

Since the function is an object, you can pass the function directly through the arguments, or you can use the function as the return value.
function Calfun (fun,arg) {
The first argument is a function object
return Fun (ARG);
}

function sum (num) {
return num+100;
}

function say (str) {
Alert ("Hello" +str);
}
Called the Say function
Callfun (say, "JS"); Hello JS
The SUM function is called
Alert (Callfun (sum,100)); 200

function Fun1 (ARG) {
var rel = function (num) {
return arg+num;
}
return rel;
}//Returns a function object
F is a function object that can complete the invocation
var f = fun1 (20);
alert (f); function (num) {return arg+name;}
Alert (f (30)); 50

var arr = [1,2,33,12,198];
Arr.sort ();
Alert (arr); 1,12,198,33 for JS, the default is to sort by string.

If we want to sort by number size, you can do this by:
function Sortbynum (A, b) {
Return parseint (a)-parseint (b);
}
Arr.sort ();
Alert (arr); 1,2,12,33,198

Sort by Object
function Person (name,age) {
This.name=name;
This.age=age;
}

var p1 = new Person ("John", 23);
var p2 = new Person ("Lemo", 39);
var p3 = new Person ("Ada", 41);

var PS = [P1,P2,P3];

Ps.sort (Sortbyage);
Ps.sort (Sortbyproperty ("Age"));

function Sortbyname (obj1,obj2) {
Return obj1.name>obj2.name?1: (obj1.name==obj2.name?0:-1);
}//Sort by name
function Sortbyage (obj1,obj2) {
return obj1.age-obj2.age;
}//Sort by age

The problem with this approach to sorting is the need to create a function for each attribute, which is obviously inflexible
But it is not the same if you call through the function's return value.
function Sortbyproperty (PropertyName) {
var sortfun = function (obj1,obj2) {
Return obj1[propertyname]>obj2[propertyname]?1: (obj1[propertyname]==obj2[propertyname]?0:-1);
}
return sortfun;
}

original articles such as reproduced, please indicate the source, this article started in CSDN website: http://blog.csdn.net/magneto7/article/details/24724299

JS: Deep function (function is Object)

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.