Last active
July 6, 2017 07:15
-
-
Save agoalofalife/9dfd616fe76d74b3ecc54009136bc53b to your computer and use it in GitHub Desktop.
function overloading depend count arguments js
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 addMethod(object, name, fn) { | |
var old = object[name] | |
object[name] = function(){ | |
console.log(fn, 'fn') | |
if (fn.length == arguments.length) { | |
return fn.apply(this, arguments) | |
} else if (typeof old == 'function') { | |
return old.apply(this, arguments) | |
} | |
} | |
} | |
var ninja = {} | |
addMethod(ninja, 'whatewer', function(){ | |
console.log('not arguments') | |
}) | |
addMethod(ninja, 'whatewer', function(a){ | |
console.log('arguments', a) | |
}) | |
addMethod(ninja, 'whatewer', function(a,b){ | |
console.log('arguments', a + " and " + b) | |
}) | |
console.log(ninja.whatewer) | |
console.log(ninja.whatewer('some')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Таким образом мы можем добавлять действия в зависимости от количества аргументов.