How to wrap Javascript function within function expression?

1k views Asked by At

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?

2

There are 2 answers

0
Bergi On BEST ANSWER

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);
0
MetallimaX On

Altering a method is done like that:

Printer.prototype._printSth = wrap(Printer.prototype._printSth, beforeFunc);