Created
October 26, 2011 18:44
-
-
Save cowboy/1317345 to your computer and use it in GitHub Desktop.
Method overloading for JavaScript
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
// 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.'); | |
} | |
}; | |
}; | |
}()); |
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
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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ECMAScript 3 compatibility +
[[Class]]
detection: https://gist.github.com/1317416/