Instanceof 在 iframe 中失败

Instanceof fails in iframe

下面的代码returns true.

console.log(document.createElement('script') instanceof Element);


<iframe> 上下文中做同样的事情 returns false:

let iframe = document.querySelector('iframe');
iframe = iframe.contentDocument || iframe.contentWindow.document;

console.log(iframe.createElement('script') instanceof Element);

Demo

这是为什么?

这是因为:

1) Element其实就是window.Element

2) 在 JS 中没有 "class" 这样的东西。一切(几乎)都是对象。因此 instanceof 检查 Prototype ancestry。当你问 is some DOM node instanceof Element 时,你可以将其翻译成 someDOMNode.prototype === Element.

3) window.Element !== document.querySelector('iframe').contentWindow.Element!!!

这将按预期记录 true

console.log(iframe.createElement('script') instanceof  document.querySelector('iframe').contentWindow.Element);