Instanceof 在 iframe 中失败

Zen*_*noo 4 javascript iframe instanceof

以下代码返回true.

console.log(document.createElement('script') instanceof Element);
Run Code Online (Sandbox Code Playgroud)


<iframe>上下文中执行相同的操作会返回false

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

console.log(iframe.createElement('script') instanceof Element);
Run Code Online (Sandbox Code Playgroud)

演示

这是为什么?

Ser*_*hiv 7

这是因为:

1)Element实际上是window.Element

2)在JS中没有“类”这样的东西。一切(几乎)都是一个对象。所以 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);
Run Code Online (Sandbox Code Playgroud)

  • 那是……我没想过要检查的东西……谢谢! (2认同)