It is indeed very convenient to use the method reload in .NET. Can I also do it in Javascript?
In Javasciprt, there is no function of overloading method. In the past, many people might have done it by directly passing the parameters less and then deciding how to deal with them based on whether the parameters are "undefined" and undefined, so as to realize the functions of overloading similar methods.
For example:
The code copy 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 Ajaxian about the writing of Javascript method overloading, which can be implemented through another method.
Take a look at this code:
The code copy 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("passed in the parameter is a, called "+name);
});
addMethod(this,"find",function(name,value){
alert(" passed in two parameters, one is called name="+name+" and the other is called value="+value);
});
};
var userinfo = new UserInfo();
userinfo.find();
userinfo.find('Who am I?');
userinfo.find('XXX','1512412514');
Look, this makes it simple...