[フレーム]
Last Updated: August 26, 2019
·
27.16K
· steveniseki

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

1 Response
Add your response

in find() correctly should be:
if (arguments.length === 1 && typeof(arguments[0]) === 'string')

over 1 year ago ·

AltStyle によって変換されたページ (->オリジナル) /