Created
September 6, 2011 18:13
-
-
Save kratkar/1198482 to your computer and use it in GitHub Desktop.
Overload funcion in javascript
This file contains 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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
other realization:
http://ejohn.org/blog/javascript-method-overloading/#postcomment
http://habrahabr.ru/blogs/javascript/86403/
etc...