Javascript simulate C # method Overloading

Source: Internet
Author: User

Every time I read John resig's blog, there will be great gains! This time I will share with you an example of simulating the C # method overload using JavaScript.

Function loadmethod (object, name, FN ){
VaR old = object [name];
If (old)
Object [name] = function (){
If (fn. Length = arguments. length)
Return fn. Apply (this, arguments );
Else if (typeof old = 'function ')
Return old. Apply (this, arguments );
};
Else
Object [name] = FN;
}

The following is an example function usercount (){
Loadmethod (this, "find", function (list ){
// Find all quantity
VaR I = 0;
Return list. length;
});
Loadmethod (this, "find", function (list, PWD ){
// Find the number of users with a specific Password
VaR K = 0;
For (VAR I = 0; I <list. length; I ++)
{
If (list [I]. Pwd = PWD)
K ++;
}
Return K;
});
Loadmethod (this, "find", function (list, ID, PWD ){
// Find the number of users with a specific password and ID
VaR K = 0;
For (VAR I = 0; I <list. length; I ++)
{
If (list [I]. ID = ID & list [I]. Pwd = PWD)
K ++;
}
Return K;
})
}

// Define a set
VaR userlist = new array ();
Userlist. Push ({ID: "holygrace", PWD: "12345 "});
Userlist. Push ({ID: "jiangyuyang", PWD: "2233 "});
Userlist. Push ({ID: "liyanhong", PWD: "12345 "});
Userlist. Push ({ID: "mayun", PWD: "ADF "});
Userlist. Push ({ID: "wangzidong", PWD: "3456 "});

VaR COUNT = new usercount ()
Alert ("find (userlist) Find \ n" + count. Find (userlist) + "bit ");
Alert ("find (userlist, \" 12345 \ ") Find \ n" + count. Find (userlist, "12345") + "bit ");
Alert ("find (userlist, \" holygrace \ ", \" 12345 \ ") Find \ n" + count. find (userlist, "holygrace", "12345") + "bit ");

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.