How do I modify/extend a javascript function in place by an inject script?
Lets say this function...
function foo(param){
// original works
}
开发者_开发百科
is already in-place in an html document.
I have a bookmarklet that injects an external script to the document. From that script, I want to modify the behavior of foo() function into this...
function foo(param){
// original works
bar(param);
}
bar() is a new function in the injected script. I have no problem duplicating foo in the injected script.
How do I do this?
Everything in javascript can be an object, including functions. With this in mind, you can create a duplicate of the old function, then override the new one while referencing the duplicate:
function foo(param){
// original works
}
var old_foo = foo;
function foo(param) {
old_foo(param);
bar(param);
}
精彩评论