How to call the Calling Function on a Function.Prototype

55 views Asked by At

When creating a Function.prototype how do you extract the function that is calling the prototype method without having the specify the function names? I have been researching and found that Javascript doesn't have super functionality, however all of the replacement methods that I have found seem to require using specific method names. Super with Known Prototype However, I want to be able to call the super of the Function.prototype without the prototype being on a specific constructor function.

Function.prototype.wrap = (func) => {
  return (...args)=>{
     return func(/*Function Caller*/, ...args);
  }
}

function testFunc(arg){
  console.log(arg);
}

testFunc = testFunc.wrap((originalFunction, args){
  console.log("Testing Wrap ---");
  originalFunction(args);
};

How can a pull the function that is calling the Function.prototype.wrap method and inject it into the secondary function without specifying the function names.

1

There are 1 answers

0
G0ldenSp00n On BEST ANSWER

Arrow functions are lexical scoped, meaning that when writing an arrow function as a prototype method the this is inherited from the current scope, making it bind to the window object. This prevented the this keyword from binding to the function that called .wrap, and meant the code didn't work as expected.

Solution

Function.prototype.wrap = function (func) {
    return (...args)=>{
       return func(this, ...args);
    }
}