非递归地替换内置的 javascript 函数
我在这里写了一些书签,我有一些与内置 javascript 函数相关的问题。
假设我想替换内置提示功能(不一定在书签中)。这看起来很简单,但是有没有办法从这个替换中调用内置提示函数?
prompt = function(message){
var tmp = prompt(message);
hook(tmp);
return tmp;
}
我无法正确确定范围;这个例子产生无限递归。
还有一种方法可以恢复已被替换的内置 javascript 函数的默认行为(无需附加额外的引用)。
I am writing some bookmarklets here and I have some questions related to built-in javascript functions.
Let's say I want to replace the built-in prompt function (not necessarily in a bookmarklet). That seems easy enough, but is there a way to call the builtin prompt function from within this replacement?
prompt = function(message){
var tmp = prompt(message);
hook(tmp);
return tmp;
}
I couldn't get the scoping to work out right; this example yields infinite recursion.
Also is there a way to restore the default behavior of a builtin javascript function that has been replaced (without hanging on to an extra reference).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将其包装在(自动执行)函数中可确保
old_prompt
不会泄漏到外部。不过,您确实需要公开一些东西。我选择提供一个进行恢复的函数,是为了方便,也许,可以说,是面向未来和封装的。只要高阶函数避免摆弄其他人的范围...另外,不,(我假设)不可能在没有任何引用的情况下恢复变量的先前值(旧值),即使该值恰好是内置的。即使有可能,这也会是一个相当晦涩的技巧——这种方法有效,所以让我们坚持下去。
(
func.restore
归功于 Martijn)Wrapping it up in a (self-executing) function ensures that
old_prompt
doesn't leak to the outside. You do need to expose something though. I chose to provide a function doing the restoring, for convenience and perhaps, one could say, future-proofing and encapsulation. As long as higher order functions refrain from fiddling with someone else's scope...Also, no, it's (I'd assume) not possible to restore the previous value of a variable without any reference to it (the old value), even if that value happened to be a built-in. Even if it was possible, it'd be a pretty obscure trick - this way works, so let's just stick with it.
(Credit for
func.restore
goes to Martijn)