JS恢复默认/全局功能

Geo*_*sen 7 javascript default global restore function

这是一个假设的问题,它确实没有实际用途,但......

假设你要这样做:

document.open = null;
Run Code Online (Sandbox Code Playgroud)

如何将document.open恢复到其原始功能,这是否可行(没有用户制作的临时存储)?document.open是否以不太知名的名称存储在另一个位置?谢谢!:)

Thi*_*ter 9

覆盖document.open创建open直接在document对象上命名的变量/函数.但是,原始函数不是在对象本身而是它的原型 - 所以你确实可以恢复它.

open功能来自于HTMLDocument.prototype您可以使用它来访问它HTMLDocument.prototype.open.

要直接调用它,请使用.call()指定要在其上使用它的对象:

HTMLDocument.prototype.open.call(document, ...);
Run Code Online (Sandbox Code Playgroud)

您也document.open可以通过简单地分配它来恢复它:

document.open = HTMLDocument.prototype.open;
Run Code Online (Sandbox Code Playgroud)

但是,请记住,HTMLDocument因此document是主机对象,通常最好不要弄乱它们 - 特别是在IE中,如果你这样做,事情可能会变得混乱.

  • 对于像“alert”这样的东西,人们会如何做呢?即用自定义函数覆盖 `window.alert` 相当简单,但是在不保留临时引用的情况下回滚是具有挑战性的:http://jsfiddle.net/ovfiddle/kcLBd/ (2认同)

小智 5

delete document.open;
Run Code Online (Sandbox Code Playgroud)

这不直观,但是在自定义函数上使用 delete 关键字将恢复原始函数,至少只要原型没有被覆盖。

例子:

> console.log
function log() { [native code] }

> console.log = function() { }
function () { }

> console.log("Hello world");
undefined

> delete console.log;
true

> console.log("Hello world");
Hello world
Run Code Online (Sandbox Code Playgroud)

与 document.open 和其他内置函数的工作方式相同。


fca*_*ran 1

var temp = document.open;
document.open = null;
Run Code Online (Sandbox Code Playgroud)

然后你恢复原来的功能

document.open = temp;
Run Code Online (Sandbox Code Playgroud)