Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

node.js - How to wrap Javascript function within function expression?

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?

question from:https://stackoverflow.com/questions/65869012/how-to-wrap-javascript-function-within-function-expression

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...