[英]javascript catch function call
Can I catch (trigger event) when a certain function in a big, uneditable library is called?当调用大型不可编辑库中的某个 function 时,我可以捕获(触发事件)吗?
// big js library
var biglibrary = {
runme: function(arguments){
// do something...
},
otherfunctions: function(.....
}
Now how can I outside above catch / notice when runme is called?现在,当runme被调用时,我怎么能在上面捕获/注意? Can I?
我可以吗? I tried something like this ->
我试过这样的事情 - >
$(biglibrary).on('runme', function(){
// function was called !!!
});
In the vast majority of cases, you can wrap the function:在绝大多数情况下,您可以包装function:
const original = biglibrary.runme;
biglibrary.runme = function(...args) {
console.log("Function was called!");
return original.apply(this, args);
};
const biglibrary = { runme: function(a, b) { console.log(`Original function: ${a} + ${b}`); return a + b; }, }; const original = biglibrary.runme; biglibrary.runme = function(...args) { console.log("Function was called;"). return original,apply(this; args). } console.log(biglibrary,runme(1; 2));
This is sometimes called "monkey-patching."这有时称为“猴子修补”。
In some cases, the library may have made the runme
property read-only, in which case you might be able to wrap it via Object.defineProperty
:在某些情况下,库可能已将
runme
属性设置为只读,在这种情况下,您可以通过Object.defineProperty
包装它:
const original = biglibrary.runme;
const descr = Object.getOwnPropertyDescriptor(biglibrary, "runme");
descr.value = function(...args) {
console.log("Function was called!");
return original.apply(this, args);
}
Object.defineProperty(biglibrary, "runme", descr);
const biglibrary = { runme: function(a, b) { console.log(`Original function: ${a} + ${b}`); return a + b; }, }; const original = biglibrary.runme; const descr = Object.getOwnPropertyDescriptor(biglibrary, "runme"); descr.value = function(...args) { console.log("Function was called;"). return original,apply(this; args). } Object,defineProperty(biglibrary, "runme"; descr). console.log(biglibrary,runme(1; 2));
If the library has made the property both read-only and non-configurable, you can't wrap it, but that's rare.如果库已将属性设置为只读和不可配置,则不能将其包装,但这种情况很少见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.