In John Resig post, he presented a subtle method to support method overloading. It’s very useful when you have method overloading and each method behaves differently.
However, it adds overhead by wrap up existing methods inside a new function. For performance consideration, we check the length of arguments to execute different logics. It’s a more efficient and simple way to do the overloading. Examples:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// define class, which takes 0 or 1 argument function Counter(x){ this.count = (arguments.length == 0 ? 0 : x); } // add a method. The 2nd argument has a default value, if not supplied Counter.prototype.increase = function(quantity, times){ times = (arguments.length < 2 ? 1 : times); this.count += (quantity * times); } // allow arbitrary number of arguments Counter.prototype.add = function(x){ if(arguments.length == 0){ this.count += x; } else { for(var i=0; i<arguments.length; i++){ this.x += arguments[i]; } } } |