代码之家  ›  专栏  ›  技术社区  ›  Zenoo

Instanceof在iframe[duplicate]中失败

  •  2
  • Zenoo  · 技术社区  · 7 年前

    下面的代码返回 true .

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

    以同样的方式 <iframe> 上下文返回 false :

    let iframe = document.querySelector('iframe');
    iframe = iframe.contentDocument || iframe.contentWindow.document;
    
    console.log(iframe.createElement('script') instanceof Element);
    

    Demo

    为什么?

    1 回复  |  直到 7 年前
        1
  •  7
  •   Sergiu Paraschiv    7 年前

    这是因为:

    1) Element window.Element

    2) 在JS中没有所谓的“类”。一切(几乎)都是一个物体。所以instanceof检查 原型祖先 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);