不能读取元素.firefox中的原型

can't read Element.prototype in firefox

本文关键字:原型 firefox 元素 不能读 读取 不能      更新时间:2023-09-26

如果我运行这个javascript:

var a,b=Element.prototype;
for(a in b)b[a];

Firefox给了我这个错误:

TypeError: Value does not implement interface Element.

下面是一个测试用例:http://codepen.io/WilliamMalo/pen/AJkuE

它可以在所有其他浏览器中工作。我怎样才能使它在firefox中工作?快把我逼疯了!

Firefox(和最近的IE)在这里的行为是因为某些属性(比如firstChild)的属性getter在原型对象上,但这些属性在原型本身上没有意义。把它们放在原型上会出错。

事实上,

这是规范所要求的行为。参见http://dev.w3.org/2006/webapi/WebIDL/#dfn-attribute-getter step2 substep2 substep2。Firefox和IE遵循此规范,而基于webkit的浏览器则没有。

考虑以下内容:

console.log('parentNode' in Element.prototype
   ? Element.prototype.parentNode
   : 'no parentNode here');

很无辜,对吧?它给你no parentNode字符串在Chrome(可能也在Safari)…但是在Firefox(21)和IE(10)中都失败了:

  • Firefox: value does not implement interface Node
  • ie10: invalid calling object

为什么?看,我们进入了主机对象区域,也被称为无规则区域。关键是,虽然有些属性似乎附加到Element.prototype,但它们无法从那里访问-只能从Element实例访问。

我们能做些什么?一个明显的解决方法是将违规者包装在"try-catch"块中:

var a, b = Element.prototype, arr = [];
for (a in b) {
  try {
    b[a];
    arr.push(a); 
  } catch (e) {}
}

您可能想尝试在循环中使用Object.getOwnPropertyDescriptor(),而不是使用原型上的键直接访问每个属性:http://codepen.io/seraphzz/pen/aJgcr