JavaScript function overloading
This is an example of function overloading in JavaScript
http://ejohn.org/blog/javascript-method-overloading/
function _add(object, name, fn){
var old = object[ name ];
if ( old )
object[ name ] = function(){
if ( fn.length == arguments.length )
return fn.apply( this, arguments );
else if ( typeof old == 'function' )
return old.apply( this, arguments );
};
else
object[ name ] = fn;
}
Now use the function overloading
function Users(){}
_add(Users.prototype, "find", function(){
// Find all users...
});
_add(Users.prototype, "find", function(name){
// Find a user by name
});
_add(Users.prototype, "find", function(first, last){
// Find a user by first and last name
});
var users = new Users();
users.find(); // Finds all
users.find("John"); // Finds users by name
Written by Steven Anavay
Related protips
2 Responses
For me, this technique is harder to read over putting the logic to inpsect the arguments
array inside your object's function, and then make decisions on the logic to apply. I might use a closure like this:
(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);
}
})();
over 1 year ago
·
Thanks Steve,
I think your version is really nice. I am going to give it a try and might change to this approach in the future.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Function
Authors
Chip Castle
21.64K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#