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

查看:191
本文介绍了以编程方式将代码添加到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代码附加或添加到其中那个功能。原因主要是在原始的不可触摸的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");
}

你这样做......

You'd do this...

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 来致电缓存的功能。这使我可以保留这个的预期值,并传递任何作为单个参数传递的参数,而不管有多少参数。

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天全站免登陆