将脚本插入现有函数?

sup*_*lle 3 javascript jquery

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

cool.lol = function () {

    // contents here

}
Run Code Online (Sandbox Code Playgroud)

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

像这样:

cool.lol = function () {

    // contents here

    // i would like to add my own stuff here!!!
}
Run Code Online (Sandbox Code Playgroud)

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

Jos*_*eph 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();?
Run Code Online (Sandbox Code Playgroud)

  • 与匿名功能很好的接触.显然,这里唯一需要注意的是,你无法访问`cool.lol`原始命名空间中的变量. (2认同)