Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Java-esque method overloading for JavaScript.
// Don't actually use this. Ever. Thx.
(function() {
var getClass = {}.toString, slice = [].slice, classNames = {
"[object Function]": "Function",
"[object Array]": "Array",
"[object String]": "String",
"[object Boolean]": "Boolean",
"[object Number]": "Number",
"[object Date]": "Date",
"[object RegExp]": "RegExp"
function getClassOf(value) {
var className;
if (value === null) {
return "Null";
} else if (value == null) {
return "Undefined";
className =;
return classNames.hasOwnProperty(className) ? classNames[className] : "Object";
Function.overload = function(obj) {
return function() {
var signature = [], length = arguments.length;
while (length--) signature[length] = getClassOf(arguments[length]);
signature = signature.join(", ");
if (obj[signature]) {
return obj[signature].apply(this, arguments);
} else {
throw new Error('Signature "' + signature + '" 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.

This is cool as hell. :clap:


Why, className) instead of classNames.hasOwnProperty(className) ?


Also, this should probably handle Null and Undefined too :D


@cowboy is an unfortunate habit acquired from using the toString, slice, and isPropertyOf boilerplate in nearly all my projects. :fish: Thanks for catching that; I've updated the code to support Null and Undefined as well.


You could also do:

if (value === null) {
  return "Null";
} else if (value == null) {
  return "Undefined";

@cowboy Sure. I thought typeof value == "undefined" would have been more readable, but value == null is far shorter.


That's what well-thought-out comments are for!


Indeed! :fish:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.