0

I came across this code while trying to understand how the JavaScript engine interprets wrapper functions. I want to know what are the steps the engine takes when it executes wrapper function code and i want to know what the this refers to in the context of a wrapped function when it is passed around to another variable that executes it later.

function profile(func, funcName) {
       return function () {
    var start = new Date(),
      returnVal = func.apply(this, arguments),
      end = new Date(),
      duration = stop.getTime() - start.getTime();

    console.log(`${funcName} took ${duration} ms to execute`);
    return returnVal;
  };
}

var profiledMax = profile(Math.max, 'Math.max');
profiledMax.call(Math, 1, 2);
sens
  • 11
  • 1
    There is nothing special about wrapper functions. A function is a function. Code is code. Execution rules are exactly the same. "*i want to know what the this refers to in the context of a wrapped function when it is passed around to another variable that executes it later.*" [How does the "this" keyword work, and when should it be used?](https://stackoverflow.com/q/3127429) and [How to access the correct `this` inside a callback](https://stackoverflow.com/q/20279484) explain `this` very well. – VLAZ Jun 24 '22 at 18:01
  • I read through the links you provided, but i still do not understand what this refers to. The wording of the post i cant follow. Does this keyword in a callback function bound to the outside function which the wrapped function is written, if so "this" in my problem is bound to profile then when i call profiledMax .call(Math, 1, 2) but what is profiledMax.call("Math", 1, 2) refer to in the profile function now. – sens Jun 24 '22 at 23:22
  • The first parameter of `.call()` becomes the value of `this` for the function. Therefore, `profiledMax .call(Math, 1, 2)` - invokes `profiledMax` and uses `Math` as the value of `this`. `profiledMax.call("Math", 1, 2) ` invokes `profiledMax` and uses the *string* `"Math"` as the value of this. Since it's a primitive, it gets converted to a String object, so it's the same as having `this = new String("Math")` – VLAZ Jun 28 '22 at 18:43

0 Answers0