3

此功能内置在页面中,我无法修改原始 .js 文件:

cool.lol = function () {

    // contents here

}

有没有办法让我用我自己的一些脚本附加这个函数?

像这样:

cool.lol = function () {

    // contents here

    // i would like to add my own stuff here!!!
}

或者有没有办法让我检测到该函数已被执行,以便我可以在它之后运行一些东西?

4

5 回答 5

10

下面是一个演示。更新为使用闭包并消除对临时变量的需要。

//your cool with lol
var cool = {
    lol: function() {
        alert('lol');
    }
}

//let's have a closure that carries the original cool.lol
//and returns our new function with additional stuff

cool.lol = (function(temp) { //cool.lol is now the local temp
    return function(){       //return our new function carrying the old cool.lol
        temp.call(cool);     //execute the old cool.lol
        alert('bar');        //additional stuff
    }
}(cool.lol));                //pass in our original cool.lol

cool.lol();
cool.lol();​
于 2012-05-25T02:39:25.937 回答
1

http://jsfiddle.net/Pcxn5/1/

// original definition which you can't touch
var cool = {
    lol: function() {
        alert("test");
    }
}
//

// your script
var ori = cool.lol;
cool.lol = function() {
    ori();
    alert('my test');
}

cool.lol();​
于 2012-05-25T02:40:13.553 回答
1

您可以覆盖该功能:

// The file you can't touch has something like this
var cool = {};
cool.lol = function () {
    console.log("original");
}

// Keep a copy of the original function.
// Override the original and execute the copy inside
var original = cool.lol;
cool.lol = function () {
    original();
    console.log("modified");
}

// Call
cool.lol();​ // logs "original", then "modified".

http://jsfiddle.net/K8SLH/

于 2012-05-25T02:41:13.370 回答
1

在不创建污染公共范围的变量的情况下:

 //let's have your cool namespace
var cool = {
    lol: function() {
        alert('lol');
    }
}

//temporarily store
cool.lol_original = cool.lol;

//overwrite
cool.lol = function() {
    this.lol_original(); //call the original function
    alert('bar');    //do some additional stuff
}

cool.lol();​
于 2012-05-25T02:48:31.443 回答
1

JavaScript 允许你

  • 以字符串形式获取函数的代码
  • 通过提供带有代码的字符串来创建新函数

每个对象都有一个toString()方法。对于函数,它返回它们的代码(除非被覆盖)。

cool.lol.toString();

返回function() { // contents here }

让我们从这个字符串中提取函数的主体。它紧随其后{,包括除最后一个之外的所有内容}

var code = cool.lol.toString();
var body = code.substring(code.indexOf('{') + 1, code.length - 1);

然后我们添加更多的东西

var newBody = body + '// i would like to add my own stuff here!!!';

Function并使用构造函数创建一个新函数。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function

cool.lol = new Function(newBody);

当然,如果新函数还必须保留参数(您必须从函数代码中解析出它们,然后将它们作为参数提供给Function构造函数),则还有更多工作要做。为简单起见,在这种情况下,我假设该函数没有参数。

一个示例实现:

http://jsfiddle.net/QA9Zx/

于 2012-05-25T02:53:08.590 回答