javascript - 如何在 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 方法的函数并将其注入辅助函数。
解决方案
箭头函数是词法作用域的,这意味着当编写箭头函数作为原型方法时,this 是从当前作用域继承的,使其绑定到窗口对象。这阻止了 this 关键字绑定到调用 .wrap 的函数,并且意味着代码没有按预期工作。
解决方案
Function.prototype.wrap = function (func) {
return (...args)=>{
return func(this, ...args);
}
}
推荐阅读
- azure - 如何批量删除(比如数百万)分布在 Cosmos db sql api 中数百万个逻辑分区的文档?
- react-native - React Native:垂直和水平对齐同一行中的图像和文本
- r - 如何在 R 中使用 group by 计算文本列值的数量?
- three.js - 如何使用threejs在iPhone上启用视网膜分辨率render.setSize
- javascript - 更改切换复选框时使用 javascript POST 布尔值
- node.js - Stripe Firebase 云函数 - res.send() 不是函数
- r - 如何删除字符串中的特定模式?
- excel - 导出为 PDF 仅打开第二个图表
- android - 我一起使用 Glide 和 RecyclerView 但它没有按我的意愿滚动
- python - WGAN 的训练循环在我们的自定义数据集上返回零损失