[英]How to monkey-patch a function declared inside another function
Say I have the following code:假设我有以下代码:
window.foo = function() {
bar();
function bar() {
console.log('hello');
}
}
/* insert monkey-patching code here */
foo();
What code can I replace /* insert monkey-patching code here */
with in order to make this eg write goodbye
instead of hello
on the console?我可以用什么代码替换
/* insert monkey-patching code here */
以使其例如在控制台上写goodbye
而不是hello
?
I have tried the following in order to override bar
, but it does not work:我尝试了以下方法来覆盖
bar
,但它不起作用:
window.foo = function() {
bar();
function bar() {
console.log('hello');
}
}
window.bar = function() {
console.log('goodbye');
}
window.foo.bar = function() {
console.log('goodbye');
}
foo();
You can't.你不能。
The function is stored in a local variable inside foo
.该函数存储在
foo
内的局部变量中。 It isn't accessible from outside that function.无法从该函数外部访问它。
You would need to either:您需要:
foo
foo
foo
so bar
was declared in a wider scope (and accessible from where you want to change it)foo
以便bar
在更广泛的范围内声明(并且可以从您想要更改的位置访问它)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.