Skip to content

Instantly share code, notes, and snippets.

@kratkar
Created September 6, 2011 18:13
Show Gist options
  • Save kratkar/1198482 to your computer and use it in GitHub Desktop.
Save kratkar/1198482 to your computer and use it in GitHub Desktop.
Overload funcion in javascript
var overloadMethod = (function () {
var functionsByLength = []
function RunOverLoadFunction() {
//console.log(arguments.length)
if( typeof(functionsByLength[arguments.length]) == 'function' )
functionsByLength[arguments.length]()
else {
throw new ReferenceError('function is not defined')
}
}
return function (obj, prop) {
obj.__defineGetter__(prop, function () {
return RunOverLoadFunction;
})
obj.__defineSetter__(prop, function (value) {
functionsByLength[value.length] = value
})
}
})()
//Examples:
obj = {
prop: 'val'
}
overloadMethod(obj, 'actions');
obj.actions = function () {
console.log('actions 0 arguments')
}
obj.actions = function (a, b) {
console.log('actions 2 arguments')
}
obj.actions()
obj.actions(1, 2)
obj.actions(1,2,3)// oops not defined
@kratkar
Copy link
Author

kratkar commented Sep 6, 2011

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