添加code JavaScript函数编程 [英] Adding code to a javascript function programatically

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

问题描述

我试图定义现有的JS库,而无需修改原有的JS code。这code加载在几个外部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");
}

我希望能够以某种方式追加或prePEND一些JS code到该功能。究其原因主要是在原始碰不得JS功能为pretty巨大的,如果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.
Thanks.

推荐答案

如果 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;
    };
})();

这里的小提琴

请注意,我用。适用来调用缓存的功能。这让我保留的预期值将此,并传递作为单独的参数传递参数的任何不论多少有。

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.

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

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