bdadoa
Last Updated: February 25, 2016
·
6.795K
· steveniseki
Stevenm

JavaScript function overloading

This is a simple example of function overloading in JavaScript using closures to overload a Users.find() method, we can overload the method with either a name or a first name, last name.

Thanks to Steve Jansen http://steve-jansen.github.io/ for this example

(function(){
 function findAll() {
   // Find all users...
  }

 function findByFullName(name) {
  // Find a user by name
  }

  function findBySurname(first, last) {
     // Find a user by first and last name
  }

  Users.prototype.find = function find() {
    if (arguments.length === 0)
       return findAll.apply(this);

    if (arguments.length === 1 and typeof(arguments[1]) === 'string')
      return findByFullName.apply(this, arguments);

   // by default, search using first and last name
   return findBySurname.apply(this, arguments);
  }
})();
Say Thanks
Respond

1 Response
Add your response

20746
Szzueolm normal
over 1 year ago ·