我想了解 Monkey-patch 在 JavaScript 中如何工作背后的概念?
我看了太多例子但无法理解
例如 - Monkey 修补 Redux 中的调度函数
let next = store.dispatch
store.dispatch = function dispatchAndLog(action) {
console.log('dispatching', action)
let result = next(action)
console.log('next state', store.getState())
return result
}
来源:http://redux.js.org/docs/advanced/Middleware.html#attempt-3-monkeypatching-dispatch
Can anyone please explain monkey patching in simple terms and example
哪些场景最适合使用它?
谢谢。
最佳答案
假设您使用一个库,该库定义了带有方法测试的类 Test。
如果你想对其进行猴子修补,你必须使用这种代码并将其包含在库之后:
// replacing current implementation with a new one
Test.prototype.test = function(arg1, arg2, ...){...}
现在假设您想做一些更聪明的事情,例如向函数添加一些内容而不修改其余部分,这里是您的做法:
var oldFN = Test.prototype.test;
Test.prototype.test = function([arguments...]){
[...some custom code...]
oldFN.apply(this, arguments);// arguments keyword refer to the list of argument that your function recevied, if you need something else use call.
[...some custom code...]
}
猴子补丁是有效的,但必须明智地使用。此外,每次升级库时,您都必须检查所有补丁是否仍然正常工作。
关于javascript - 了解 Javascript 中的猴子补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37020630/