gpt4 book ai didi

javascript - 如何干净地猴子修补 Javascript 中的函数?

转载 作者:行者123 更新时间:2023-12-01 15:22:13 25 4
gpt4 key购买 nike

具有低级 C/汇编编程背景,我想知道的一件事是是否可以在 Javascript 中绕过一个函数,意思是用我定义的函数替换它,然后调用原始函数,以添加额外的代码或钩子(Hook)那个功能。
我已经找到了示例,但所有这些都不是我认为干净的,涉及创建其他变量等

最佳答案

许多框架都大量使用 Javascript 中的猴子补丁,例如 zone.js 补丁 异步操作 (对于 Angular )。

解决方案1: 猴子补丁最简单的方法如下。

var orig_setTimeout = window.setTimeout;

window.setTimeout = function setTimeout(fn, ms) {
// your patching code goes here
return orig_setTimeout(fn, ms);
}

解决方案 2: 使用 IIFE

信用 @Annihil link
function originalFn(arg){
return console.log("originalFn is invoked with argument: " + arg);
}

var patchedFn = (function(originalFunction) {

return function(){
console.log("patched function is invoked with arguments: " + arguments)
return originalFunction.apply(this, arguments);
}
}(originalFn))


patchedFn("Hello");

// Above invocation will results in
patched function is invoked with arguments: Hello
originalFn is invoked with argument: Hello

解决方案 3: 您可以使用 ES6 代理 的应用陷阱
var patchedFn = {
apply (target, ctx, args) {
console.log("patched function is invoked with arguments: " + args)
return Reflect.apply(...arguments)
}
}
function originalFn (arg) {
return console.log("originalFn is invoked with argument: " + arg);
}
var proxyFn = new Proxy(originalFn, patchedFn);

// Now proxy function can be invoked as following

proxyFn("Hello");
proxyFn(...["Hello"]);
proxyFn.call(null, "Hello");
proxyFn.apply(null, ["Hello"]);

// All the above invocation will print the below output

patched function is invoked with arguments: Hello
originalFn is invoked with argument: Hello

解决方案 4: 您还可以查看 ES6 装饰器 。它们也可能适合您的目的。有关 ES6 装饰器的介绍,您可以关注 sitepoint

案例研究:
如果您想了解 zone.js 如何修补异步 操作,请阅读博文 monkey patching in zone.js

关于javascript - 如何干净地猴子修补 Javascript 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52945683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com