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 ");