Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created October 26, 2011 18:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboy/1317345 to your computer and use it in GitHub Desktop.
Save cowboy/1317345 to your computer and use it in GitHub Desktop.
Method overloading for JavaScript
// Don't actually use this. Ever. Thx.
(function fn() {
var slice = fn.call.bind([].slice);
Function.overload = function(obj) {
return function() {
var key = slice(arguments).map(function(a) { return typeof a; }).join(', ');
if (obj[key]) {
return obj[key].apply(this, arguments);
} else {
throw new Error('Signature "' + key + '" not defined.');
}
};
};
}());
var func = Function.overload({
'number, string': function(n, s) {
return 'The number ' + n + ' was passed, followed by string ' + s;
},
'string, number': function(s, n) {
return 'The string ' + s + ' was passed, followed by number ' + n;
}
});
func(123, 'foo') // "The number 123 was passed, followed by string foo"
func('foo', 123) // "The string foo was passed, followed by number 123"
func(123, 456) // Error: Signature "number, number" not defined.
Copy link

ghost commented Oct 26, 2011

ECMAScript 3 compatibility + [[Class]] detection: https://gist.github.com/1317416/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment