我正在尝试在不修改原始 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.
如果这是原版的话……
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
来调用缓存函数.这让我可以保留 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 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!