Why is window not identical to window.self in Internet Explorer?

后端 未结 2 1946
有刺的猬
有刺的猬 2020-12-03 13:17

There\'s a convoluted backstory involving how I came across this, but why is the self property not exactly equal to the window itself?

In Safari and Fir

相关标签:
2条回答
  • 2020-12-03 13:55

    Nice question. It does it with document and document.parentWindow too:

    window == document; // true
    window === document; // false
    
    window == document.parentWindow; // true
    window === document.parentWindow; // false
    

    The big wtf for me though is:

    window == document; // true
    document == window; // false
    

    You can swap out window with this in any of the above examples (and stay in the global context) with the same results. It makes the == operator even more suspect.

    Why it behaves this way is so beyond me.

    0 讨论(0)
  • 2020-12-03 13:59

    That's not all, window!==window.window!

    I believe what we're probably seeing here is the difference between the ‘inner window’ and ‘outer window’ objects. Certainly other browsers have these (eg. Moz); they're typically used to present a different view of the window from inside and outside its own code.

    The inner window holds your global variables and document-specific members. The outer window is accessible to [cross-frame-] scripting via window-references like frames[n], parent, opener, and apparently self. It is bound to the owner viewport (browser window/frame), so eg. when you navigate an iframe to a new document, the parent document still sees the same-identity window object in its iframe.

    In a sensible Browser Object Model design there would be separate objects for this, but when JavaScript was originally thrown together by Netscape there was very little consideration for elegance, resulting in this and many other interfaces where there is too much overload (form with an element called submit, anyone?).

    So for compatibility, the split window has to continue to appear to be a single object to scripts even though it isn't underneath. In IE, sometimes the mask slips: it seems like saying window gets you the inner window, and there's no hack to make it === against the outer window.

    ETA: Actually come to think of it, there's even some (poor) justification for this. The ECMAScript spec, which is not written with multiple global contexts in mind, defines window, and the unbound version of this, as retrieving the global variable scope object, which would be the inner window.

    The other properties, being part of the DOM/BOM, are not within the scope of the ECMA spec, so they can return something different (and must, for the sake of cross-frame scripting).

    0 讨论(0)
提交回复
热议问题