To understand monkey patching in Javascript [closed]

浪子不回头ぞ 提交于 2019-12-11 00:58:28

问题


I am trying to understand the concept behind how monkey-patch works in JavaScript?

I've gone through too many examples but couldn't able to understand

For example - Monkey patching the dispatch function in 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
}

Source: http://redux.js.org/docs/advanced/Middleware.html#attempt-3-monkeypatching-dispatch

Can anyone please explain monkey patching in simple terms and example

And which is the best scenarios to use it?

Thanks.


回答1:


Let say you use a library which define a class Test with a method test.

If you want to monkey patching-it you have to use this kind of code and include it after the library :

// replacing current implementation with a new one
Test.prototype.test = function(arg1, arg2, ...){...}

Now let say you want to do something a bit smarter, like adding something to the function without modifying the rest here is how you would do it :

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...]
}

Monkey patching is valid but must be used wisely. Furthermore each time you upgrade the library, you must check that all your patches works still fine.



来源:https://stackoverflow.com/questions/37020630/to-understand-monkey-patching-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!