Overloading Functions in JavaScript
My previous post used function overloading by different sent in statements to a when function, appended at the end of every function that needed to be overridden. This same approach applies to making functions overridable by the number of defined arguments:
var sum = (function sum(a){ return a; }).overload(); var sum = (function sum(a, b){ return a + b; }).overload(); console.log(sum(1));// 1 console.log(sum(1, 2));// 3
Basically, the implementation is nearly the same but simpler. Instead of having to evaluate a set of statements to determine which callback applies I just check the number of arguments sent in and call the corresponding callback. More details in the comments:
Function.prototype.overload = function overload(){ // Like last time a naive approach to get the function name for example purposes var funcString = this.toString(); var funcName = funcString.split('function')[1].split('(')[0].replace(' ', ''); // Same storage approach as last time but I will use the overload function to // store values instead of an external variable. Arguably this is cleaner. // Remember 'this' is the original callback and this.length gives the length of // arguments of a function. overload[funcName] = overload[funcName] || []; overload[funcName][this.length] = this; // Run the appropriate argument length constructor return function(){ if (overload[funcName][arguments.length]) return overload[funcName][arguments.length].apply(this, arguments); throw('Error: There is no defined version of function ' + funcName + ' for ' + arguments.length + ' arguments.'); }; }
Also, I should mention, although I take a very different approach, I was initially inspired by an old blog post from John Resig.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2013/overloadingFunctions.js












