0

I would like to add a wrapper function to one of my functions to show extra information.

Below is my wrapper function:

var wrap =  function(functionToWarp, before) {
 var wrappedFunction = function() {        
          
 if (before) before.apply(this, arguments);
 result = functionToWrap.apply(this, arguments);
          
 return result;
 }
      
 return wrappedFunction;
}

var beforeFunc = function(){
  // print extra infos before functionToWarp() triggers.
}

and my function _printSth to wrap:

var Printer = function () {
  this._printSth = function (input) {
    // print something from input...
  }
}
Printer._printSth = wrap(Printer._printSth, beforeFunc);

I have tried to wrap Printer._printSth by calling

Printer._printSth = wrap(Printer._printSth, beforeFunc); or similar codes but failed. How should I declare my _printSth() to be able to be wrapped?

Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
Kit Law
  • 323
  • 6
  • 15
  • Regarding the former `AOP` tag, wrapping and reassigning already declared functionality (be it functions or methods) misses any aspect of _AOP_. Any language which wants to qualify for the latter has to provide abstraction levels for at least `Joinpoint`, `Advice` and `Aspect`. The use case described by the OP should be referred to as method modification, and JavaScript of cause is well suited for this scenario and could easily provide a complete `target`/`context` aware toolset of method modifiers like `around`, `before`, `after`, `afterThrowing` and `afterFinally` via `Function.prototype`. – Peter Seliger Sep 14 '22 at 14:22

2 Answers2

2

You could write

function Printer() {
  this._printSth = function (input) {
    // print something from input...
  };
  this._printSth = wrap(this._printSth, beforeFunc);
}

or

function Printer() {
  this._printSth = wrap(function (input) {
    // print something from input...
  }, beforeFunc);
}

but that's equivalent to simply writing

function Printer() {
  this._printSth = function (input) {
    beforeFunc(input);
    // print something from input...
  };
}

Assuming you rather might want to wrap the method on a specific instance, you'd do

const p = new Printer();
p._printSth = wrap(p._printSth, beforeFunc);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

Altering a method is done like that:

Printer.prototype._printSth = wrap(Printer.prototype._printSth, beforeFunc);
MetallimaX
  • 594
  • 4
  • 13