0

In decorator patterns, the original function may be redefined like this: original = wrapper(original). Why does wrapper2 in the example below use the original aa function (a + b), if it has been redefined by thewrapper function before (a + b + 12)?

function aa(a, b) {
  return a + b
}
console.log(aa)       //function aa(a,b) {return a+b}
console.log(aa(1, 2)) //3


function wrapper(fn) {
  return function() {
    return arguments[0] + arguments[1] + 12
  }
}
aa = wrapper(aa)
console.log(aa)       //function(){return arguments[0]+arguments[1]+12}
console.log(aa(1, 2)) //15


function wrapper2(fn) {
  return function() {
    return arguments[0] + arguments[1] + 120
  }
}
aa = wrapper2(aa)
console.log(aa)       //function(){return arguments[0]+arguments[1]+120}
console.log(aa(1, 2)) //123
  • it's wrapping 120 instead of 12. would be nice if you could just curry in the third value instead of hard-coding it... – dandavis Oct 19 '15 at 08:27
  • 2
    You never use `fn`, so you arent really wrapping the previous `aa` functions. All you are doing is defining a function that will return a function that will add the first two arguments and adding a third hard coded value. – Patrick Evans Oct 19 '15 at 08:28

1 Answers1

0

you are not using fn at all. Try this one:

function wrapper(fn) {
  return function() {
    return ( fn( arguments[0], arguments[1] ) + 12 );
  }
}
pietro909
  • 1,811
  • 1
  • 19
  • 26