Example of method overload in JavaScript
This article mainly introduces methods in JavaScript to reload instances. This article provides reload instances. For more information, see
The method overload in. NET is indeed very convenient. Which Javascript can be used?
In javasrt RT, there is no function to overload methods. In the past, many people used to directly reduce the number of parameters and decide how to handle them based on whether the parameter is "undefined" or not, so as to realize the function of reload similar methods.
For example:
The Code is as follows:
Var showMessage = function (name, value, id ){
If (id! = "Undefined "){
Alert (name + value + id );
}
Else if (value! = "Undefined "){
Alert (name + value );
}
Else {
Alert (name );
}
}
ShowMessage ("Haha ");
ShowMessage ("Haha ","??");
ShowMessage ("Haha ","??", 124124 );
Today, I saw an article on Javascript method overload writing on Ajaxian, which can be implemented through another method.
Take a look at this Code:
The Code is as follows:
// AddMethod-By John Resig (MIT Licensed)
Function addMethod (object, name, fn ){
Var old = object [name];
Object [name] = function (){
If (fn. length = arguments. length ){
Return fn. apply (this, arguments );
}
Else if (typeof old = 'function '){
Return old. apply (this, arguments );
}
}
};
Var UserInfo = function (){
AddMethod (this, "find", function (){
Alert ("No parameter ");
});
AddMethod (this, "find", function (name ){
Alert ("the input parameter is" + name );
});
AddMethod (this, "find", function (name, value ){
Alert ("two parameters are passed in, one is name =" + name + "and the other is value =" + value );
});
};
Var userinfo = new UserInfo ();
Userinfo. find ();
Userinfo. find ('Who am I? ');
Userinfo. find ('xx, '123 ');
Look, it's easy.