Skip to content

Instantly share code, notes, and snippets.

@agoalofalife
Last active July 6, 2017 07:15
Show Gist options
  • Save agoalofalife/9dfd616fe76d74b3ecc54009136bc53b to your computer and use it in GitHub Desktop.
Save agoalofalife/9dfd616fe76d74b3ecc54009136bc53b to your computer and use it in GitHub Desktop.
function overloading depend count arguments js
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'))
@agoalofalife
Copy link
Author

  1. С помощью замыкания , мы замыкаем в функции переменную и аргументы.
  2. Если количество аргументов соответствует количеству параметров, то вызывается крайния добавленная функция.
  3. Если не соответсвует то вызывается ранее добавленная и сохраненная в замыкаемой переменной.
    Таким образом мы можем добавлять действия в зависимости от количества аргументов.

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