此功能内置在页面中,我无法修改原始 .js 文件:
cool.lol = function () {
// contents here
}
有没有办法让我用我自己的一些脚本附加这个函数?
像这样:
cool.lol = function () {
// contents here
// i would like to add my own stuff here!!!
}
或者有没有办法让我检测到该函数已被执行,以便我可以在它之后运行一些东西?
此功能内置在页面中,我无法修改原始 .js 文件:
cool.lol = function () {
// contents here
}
有没有办法让我用我自己的一些脚本附加这个函数?
像这样:
cool.lol = function () {
// contents here
// i would like to add my own stuff here!!!
}
或者有没有办法让我检测到该函数已被执行,以便我可以在它之后运行一些东西?
下面是一个演示。更新为使用闭包并消除对临时变量的需要。
//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();
// 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();
您可以覆盖该功能:
// 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".
在不创建污染公共范围的变量的情况下:
//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();
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构造函数),则还有更多工作要做。为简单起见,在这种情况下,我假设该函数没有参数。
一个示例实现: