3

如果我运行这个 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中工作?快把我逼疯了!

4

3 回答 3

3

The Firefox (and recent IE) behavior here is because the property getters for some properties (say firstChild) are on the prototype object bu the properties make no sense on the prototype itself. Trying to get them on the prototype will throw.

This is the behavior required by the specification, in fact. See http://dev.w3.org/2006/webapi/WebIDL/#dfn-attribute-getter step 2 substep 2 subsubstep 2. Firefox and IE are following the spec here and WebKit-based browsers are not.

于 2013-06-01T02:03:50.043 回答
1

考虑以下:

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

很无辜,对吧?它在 Chrome 中为您提供字符串(也可能在 Safari 中)......但它在 Firefox(21)和 IE(10)中都no parentNode失败了:

  • 火狐: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) {}
}
于 2013-05-31T21:44:17.750 回答
0

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

于 2013-06-01T06:30:08.843 回答