JS:在不触及原始功能的情况下调用一个接一个的函数? [英] JS: Call a function after another without touching the original function?

查看:64
本文介绍了JS:在不触及原始功能的情况下调用一个接一个的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在特定页面上扩展第三方库,但我不想更改任何第三方代码。我知道第三方库在发生事件时调用的函数的名称,所以如果我希望自己的自定义代码在那之后执行,我该怎么做?

I am trying to extend a third party library on a specific page, but I don't want to change any of the third party code. I know the name of the functions the third party library calls when something happens, so if I want my own custom code to execute after that, how can I do that?

第三方图书馆有:

function eventFinished(args){
    //library stuff here
}

现在,如果是我自己的代码,我会做这样的事情:

Now if it was my own code I'd do something like this:

function eventFinished(args){
    //library stuff here
    MyCustomFunction();
}

但是,它不是,我不想覆盖库存库代码。那么无论如何都要做到这一点,但没有触及原始的功能代码?我会引用函数本身,但就是这样。

However, it's not and I don't want to overwrite stock library code. So is there anyway to do the above, but without touching the original function code? I would have a reference to the function itself, but that's it.

编辑:我应该提到声明的函数是全局可用的。

I should mention the declared function is available globally.

推荐答案

如果你有办法获得你想扩展的函数的引用,你可以像这样猴子补丁:

If there is a way for you to get a reference to the function you want to extend you can "monkey-patch" it like this:

var fnOriginalFunction = functionYouWantToExtend;
functionYouWantToExtend = function() {
    fnOriginalFunction.apply(this, arguments);

    // your code here
};

这有效地重写了你想要以无缝方式扩展的功能。

This effectively re-writes the function you want to extend in a somewhat-seamless manner.

有关猴子修补的更多信息

这篇关于JS:在不触及原始功能的情况下调用一个接一个的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆