Created
April 17, 2018 06:59
-
-
Save wiyoe/1a0e4ffb583c88b59ce5119ceeec44e5 to your computer and use it in GitHub Desktop.
Javascript overloading.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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