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);
}
})();Written by Steven Iseki
Related protips
1 Response
in find() correctly should be:
if (arguments.length === 1 && typeof(arguments[0]) === 'string')
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Functions
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#