Method overload instances in JavaScript

  • 2020-05-17 04:44:31
  • OfStack

It is really convenient to overload the methods in NET. Can you do the same in Javascript?

In Javasciprt, Bunsen does not have the function of method overloading. In the past, many people would simply pass fewer parameters and then decide how to deal with them according to whether the parameters are "undefined" or not, so as to realize the function of method overloading.

Such as:


var showMessage = function(name,value,id){
    if(id != " undefined " ){
        alert(name+value+id);
    }
    else if(value != " undefined " ){
        alert(name + value);
    }
    else{
        alert(name);
    }
} showMessage( "Ha ha" );
showMessage( "Ha ha" , "??" );
showMessage( "Ha ha" , "??" ,124124);

Today I saw a post on Ajaxian about overloading the Javascript method, which can be implemented by another method.

Take a look at this code:


// 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 parameters" );
    });     addMethod(this, " find " ,function(name){
        alert( The parameter passed in is 1 One, called " +name);
    });     addMethod(this, " find " ,function(name,value){
        alert( "Passed in two parameters, 1 The name name= " +name+ " 1 The name value= " +value);
    });
}; var userinfo = new UserInfo();
userinfo.find();
userinfo.find(' Who am I? ');
userinfo.find(' XXX ','1512412514');

See, that makes 1 easy...


Related articles: