非递归地替换内置的 javascript 函数

发布于 2024-10-18 05:51:58 字数 311 浏览 1 评论 0原文

我在这里写了一些书签,我有一些与内置 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏见 2024-10-25 05:51:58
(function () {
    var old_prompt = prompt;
    prompt = function (msg) {
        var tmp = old_prompt(msg);
        hook(tmp);
        return tmp;
    };
    prompt.restore = function () { prompt = old_prompt; }
    // analogous for other functions you want to replace
})();

将其包装在(自动执行)函数中可确保 old_prompt 不会泄漏到外部。不过,您确实需要公开一些东西。我选择提供一个进行恢复的函数,是为了方便,也许,可以说,是面向未来和封装的。只要高阶函数避免摆弄其他人的范围...

另外,不,(我假设)不可能在没有任何引用的情况下恢复变量的先前值(旧值),即使该值恰好是内置的。即使有可能,这也会是一个相当晦涩的技巧——这种方法有效,所以让我们坚持下去。

func.restore 归功于 Martijn)

(function () {
    var old_prompt = prompt;
    prompt = function (msg) {
        var tmp = old_prompt(msg);
        hook(tmp);
        return tmp;
    };
    prompt.restore = function () { prompt = old_prompt; }
    // analogous for other functions you want to replace
})();

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文