javascriptfunctiondecoratorredefine

The original function value after it has been redefined by decorator in JavaScript


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


Solution

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

    function wrapper(fn) {
      return function() {
        return ( fn( arguments[0], arguments[1] ) + 12 );
      }
    }