在IE8中恢复被覆盖的javascript方法

Restoring an overwritten javascript method in IE8

本文关键字:javascript 方法 覆盖 IE8 恢复      更新时间:2024-01-31

我覆盖了Element原型上的许多方法,这样我就可以添加一个自定义钩子,比如:

Element.prototype._method = Element.prototype.method;
Element.prototype.method = function(){
  this._method.apply(this, arguments);
  // custom callback
}

在某个时候,我想恢复原来的方法,所以我做了:

Element.prototype.method = Element.prototype._method;

然而,当在节点上调用method元素时,它似乎在IE8中抛出了Invalid procedure call or argument错误。我是否错误地恢复了原始方法?

IE8似乎有这个问题,不太容易解决,但您可以在Element.prototype上尝试delete来恢复覆盖的。

var old = Element.prototype.getElementsByTagName;
Element.prototype.getElementsByTagName = old;
// alert(document.body.getElementsByTagName('script').length); // this throws Error
delete Element.prototype.getElementsByTagName;
alert(document.body.getElementsByTagName('script').length); // Now it works as expected