Last active
August 29, 2015 14:03
-
-
Save leeferwagen/7368e398bd48043873e3 to your computer and use it in GitHub Desktop.
Function for overloading class methods in 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
(function() { | |
'use strict'; | |
var global; | |
if (typeof window == 'object') { | |
global = window; | |
} else if (typeof exports == 'object') { | |
global = exports; | |
} | |
var trim = Function.prototype.call.bind(String.prototype.trim); | |
var tokenizeSignatur = function(signatur) { | |
var m = signatur.match(/^(.*?)\s*\((.*?)\)$/); | |
if (m === null) { | |
throw new Error('Invalid method signatur: ' + signatur); | |
} | |
var name = m[1]; | |
var args = m[2].split(',').map(trim); | |
return { | |
name: name, | |
args: args | |
}; | |
}; | |
var getArgumentType = function(arg) { | |
if (arg === undefined) return 'undefined'; | |
if (arg === null) return 'null'; | |
return arg.constructor.name; | |
}; | |
global.overloading = function Overloading(prototype, methods) { | |
for (var signatur in methods) { | |
var method = methods[signatur]; | |
var token = tokenizeSignatur(signatur); | |
if ('undefined' == typeof prototype[token.name]) { | |
Object.defineProperty(prototype, token.name, { | |
enumerable: false, | |
configurable: false, | |
writeable: false, | |
value: function() { | |
var argumentTypes = []; | |
for (var i = 0; i < arguments.length; i++) { | |
argumentTypes.push(getArgumentType(arguments[i])); | |
} | |
var signatur = token.name + '(' + argumentTypes.join(',') + ')'; | |
if ('function' != typeof this[signatur]) { | |
throw new Error('Undefined method signatur: ' + signatur); | |
} | |
this[signatur].apply(this, arguments); | |
} | |
}); | |
} | |
Object.defineProperty(prototype, signatur, { | |
enumerable: false, | |
configurable: false, | |
writeable: false, | |
value: method | |
}); | |
} | |
}; | |
}()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example
http://jsfiddle.net/MuslimIdris/nx64R/
Create a class „User“ with only one method in 3 variations
And now use the sample class