将脚本插入现有函数?

时间:2012-05-25 02:35:32

标签: javascript jquery

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

cool.lol = function () {

    // contents here

}

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

像这样:

cool.lol = function () {

    // contents here

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

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

5 个答案:

答案 0 :(得分:10)

Here's a demo of the following。更新为使用闭包并删除对临时变量的需要。

//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();​

答案 1 :(得分: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();​

答案 2 :(得分: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/

答案 3 :(得分: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();​

答案 4 :(得分: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/