以编程方式将代码添加到javascript函数

问题描述 投票:105回答:6

我正在尝试自定义现有的JS库而不修改原始的JS代码。这段代码加载了一些我有权访问的外部JS文件,我想做的是更改原始文件中包含的一个函数,而不复制并将整个文件粘贴到第二个JS文件中。 例如,关闭限制JS可能有这样的功能:

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

我希望能够以某种方式将一些JS代码附加或添加到该函数中。原因主要是在原始的不可触摸的JS中,函数非常庞大,如果JS得到更新,我覆盖它的函数将会过时。

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

javascript merge append user-defined-functions prepend
6个回答
205
投票

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

所以,如果这是原来的......

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

Here's the fiddle


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


29
投票

首先将实际函数存储在变量中..

var oldFunction = someFunction;

然后定义你自己的:

someFunction = function(){
  // do something before
  oldFunction();
  // do something after
};

10
投票

您可以创建一个调用代码的函数,然后调用该函数。

var old_someFunction = someFunction;
someFunction = function(){
    alert('Hello');
    old_someFunction();
    alert('Goodbye');
}

6
投票

我不知道你是否可以更新这个函数,但是根据它的引用方式,你可以在它的位置创建一个新函数:

var the_old_function = someFunction;
someFunction = function () {
    /* ..My new code... */
    the_old_function();
    /* ..More of my new code.. */
}

5
投票

也。如果要更改本地上下文,则必须重新创建功能。例如:

var t = function() {
    var a = 1;
};

var z = function() {
    console.log(a);
};

现在

z() // => log: undefined

然后

var ts = t.toString(),
    zs = z.toString();

ts = ts.slice(ts.indexOf("{") + 1, ts.lastIndexOf("}"));
zs = zs.slice(zs.indexOf("{") + 1, zs.lastIndexOf("}"));

var z = new Function(ts + "\n" + zs);

z() // => log: 1

但这只是最简单的例子。处理参数,注释和返回值还需要做很多工作。此外,还存在许多陷阱。 toString | slice | indexOf | lastIndexOf | new Function


0
投票

代理模式(由user1106925使用)可以放在函数中。我在下面写的那个是关于不在全局范围内的函数,甚至是原型。你会像这样使用它:

extender(
  objectContainingFunction,
  nameOfFunctionToExtend,
  parameterlessFunctionOfCodeToPrepend,
  parameterlessFunctionOfCodeToAppend
)

在下面的代码片段中,您可以看到我使用该函数来扩展test.prototype.doIt()。

// allows you to prepend or append code to an existing function
function extender (container, funcName, prepend, append) {

    (function() {

        let proxied = container[funcName];

        container[funcName] = function() {
            if (prepend) prepend.apply( this );
            let result = proxied.apply( this, arguments );
            if (append) append.apply( this );
            return result;
        };

    })();

}

// class we're going to want to test our extender on
class test {
    constructor() {
        this.x = 'instance val';
    }
    doIt (message) {
        console.log(`logged: ${message}`);
        return `returned: ${message}`;
    }
}

// extends test.prototype.doIt()
// (you could also just extend the instance below if desired)
extender(
    test.prototype, 
    'doIt', 
    function () { console.log(`prepended: ${this.x}`) },
    function () { console.log(`appended: ${this.x}`) }
);

// See if the prepended and appended code runs
let tval = new test().doIt('log this');
console.log(tval);
© www.soinside.com 2019 - 2024. All rights reserved.