如何在函数表达式中包装 Javascript 函数?

How to wrap Javascript function within function expression?

我想向我的其中一个函数添加包装函数以显示额外信息。

下面是我的包装函数:

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.
}

和我的函数 _printSth 包装:

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

我试图通过调用

来包装 Printer._printSth

Printer._printSth = wrap(Printer._printSth, beforeFunc); 或类似的代码但失败了。 我应该如何声明我的 _printSth() 才能被包装?

你可以写

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

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

但这相当于简单地写

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

假设您可能希望将方法包装在特定实例上,您会这样做

const p = new Printer();
p._printSth = wrap(p._printSth, beforeFunc);

改变一个方法是这样完成的:

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