Method Overloading using JavaScript

Advertisement
Post Pic

John Resig, has explained us a better and interesting way of Method Overloading. Here he has discussed about the ability to run different code depending on the number of arguments passed into the same function. For those who are not familiar with, it’s just a way of mapping a single function call to multiple functions based on arguments they accept.

Function:

// 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 );
    };
}

Using It:

function Users(){
   addMethod(this, "find", function(){
     // Find all users...
   });
   addMethod(this, "find", function(name){
     // Find a user by name
   });
   addMethod(this, "find", function(first, last){
     // Find a user by first and last name
   });
 }

Using object prototype:

 function Users(){}
 addMethod(Users.prototype, "find", function(){
   // Find all users...
 });
 addMethod(Users.prototype, "find", function(name){
   // Find a user by name
 });
 addMethod(Users.prototype, "find", function(first, last){
   // Find a user by first and last name
 });

End Result:

var users = new Users();
users.find(); // Finds all
users.find("John"); // Finds users by name
users.find("John", "Resig"); // Finds users by first and last name
users.find("John", "E", "Resig"); // Does nothing

Hope the above will help developers a lot!

Rock Up the Web World!!!

Related Entries...

You Might Like:

Advertisement

Please let us know your feedback about the article through the comments section below, we want to hear from you about our website. And your comment / advice may help us to serve you better in upcoming articles.

Thank You!
Vivekanand [Founder of DeveloperSnippets]

One Response

[...] stillisstillmoving.com wrote an interesting post today!.Here’s a quick excerpt John Resig, has explained us a better and interesting way of Method Overloading. Here he has discussed about the ability to run different code depending on the number of arguments passed into the same function. For those who are not familiar with, it’s just a way of mapping a single function call to multiple functions based on arguments they accept. Function: // addMethod – By John Resig (MIT Licensed) function addMethod(object, name, fn){ var old = object[ name ]; object[ name ] = function(){ [...]

Leave Your Response

* Name, Email, Comment are Required

Write For Us

Online Sponsors

Start Foreign Exchange Trading today with the Forex Affiliate Program and also you can have access Online Forex News to know what happens every single moment.


Forex Floor


Switch to our mobile site