首页 > 解决方案 > 如何在 Function.Prototype 上调用调用函数

问题描述

创建 Function.prototype 时,如何在没有指定函数名称的情况下提取调用原型方法的函数?我一直在研究,发现 Javascript 没有超级功能,但是我发现的所有替换方法似乎都需要使用特定的方法名称。Super with Known Prototype但是,我希望能够调用 Function.prototype 的 super 而原型不在特定的构造函数上。

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

如何在不指定函数名称的情况下提取调用 Function.prototype.wrap 方法的函数并将其注入辅助函数。

标签: javascriptsuperprototypal-inheritancefunction.prototype

解决方案


箭头函数是词法作用域的,这意味着当编写箭头函数作为原型方法时,this 是从当前作用域继承的,使其绑定到窗口对象。这阻止了 this 关键字绑定到调用 .wrap 的函数,并且意味着代码没有按预期工作。

解决方案

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

推荐阅读