以编程方式向 javascript 函数添加代码 [英] Adding code to a javascript function programmatically

查看:51
本文介绍了以编程方式向 javascript 函数添加代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在不修改原始 JS 代码的情况下自定义现有的 JS 库.这段代码加载了一些我可以访问的外部 JS 文件,我想要做的是更改原始文件中包含的函数之一,而无需将整个内容复制并粘贴到第二个 JS 文件中.
例如,禁区 JS 可能有这样的功能:

I'm attempting to customize an existing JS library without modifying the original JS code. This code loads in a few external JS files which I do have access to, and what I'd like to do is change one of the functions contained in the original file without copying and pasting the whole thing into the second JS file.
So for example, the off limits JS might have a function like this:

var someFunction = function(){
    alert("done");
}

我希望能够以某种方式在该函数中添加或添加一些 JS 代码.原因主要是在原始的 untouchable JS 中,函数非常庞大,如果该 JS 更新,我用它覆盖的函数将过时.

I'd like to be able to somehow append or prepend some JS code into that function. The reason is primarily that in the original untouchable JS the function is pretty enormous and if that JS ever gets updated, the function I overwrite it with will be out of date.

我不完全确定这是可能的,但我想我会检查一下.

I'm not entirely sure this is possible, but I figured I'd check.

推荐答案

如果 someFunction 是全局可用的,那么您可以缓存该函数,创建您自己的函数,并让您的人调用它.

If someFunction is globally available, then you can cache the function, create your own, and have yours call it.

所以如果这是原版...

So if this is the original...

someFunction = function() {
    alert("done");
}

你会这样做...

someFunction = (function() {
    var cached_function = someFunction;

    return function() {
        // your code

        var result = cached_function.apply(this, arguments); // use .apply() to call it

        // more of your code

        return result;
    };
})();

这是小提琴

请注意,我使用 .apply 来调用缓存函数.这让我可以保留 this 的预期值,并将传入的任何参数作为单独的参数传递,而不管有多少.

Notice that I use .apply to call the cached function. This lets me retain the expected value of this, and pass whatever arguments were passed in as individual arguments irrespective of how many there were.

这篇关于以编程方式向 javascript 函数添加代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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