Skip to content

Instantly share code, notes, and snippets.

@wiyoe
Created April 17, 2018 06:59
Show Gist options
  • Select an option

  • Save wiyoe/1a0e4ffb583c88b59ce5119ceeec44e5 to your computer and use it in GitHub Desktop.

Select an option

Save wiyoe/1a0e4ffb583c88b59ce5119ceeec44e5 to your computer and use it in GitHub Desktop.
Javascript overloading.
function overloadMethod(object, name, fn){
if(!object._overload){
object._overload = {};
}
if(!object._overload[name]){
object._overload[name] = {};
}
if(!object._overload[name][fn.length]){
object._overload[name][fn.length] = fn;
}
object[name] = function() {
if(this._overload[name][arguments.length])
return this._overload[name][arguments.length].apply(this, arguments);
};
}
function Students(){
overloadMethod(this, "find", function(){
// Find a student by name
});
overloadMethod(this, "find", function(first, last){
// Find a student by first and last name
});
}
var students = new Students();
students.find(); // Finds all
students.find("Rahul"); // Finds students by name
students.find("Rahul", "Mhatre"); // Finds users by first and last name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment