Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript this.window not equal to window

Tags:

javascript

Consider the following top-level javascript code:

if (this.window === window)
    alert('same');
else
    alert('different'); // alerts: different  

Why is this.window and window not strictly equal? I've also tried 'this' on the rhs of the expression and get the same result.

like image 577
Seth Stone Avatar asked Nov 14 '10 22:11

Seth Stone


2 Answers

In Internet Explorer (8.0.7600 is what I've tested), this with no qualifier actually resolves to the global window object. In all other browsers I've tried (Chrome, Firefox, Opera), this.window === window in that context - and, helpfully, this === window as well.

Try this in IE to verify:

if (this === window)
  alert('same');
else
  alert('different');
like image 139
Dylan Beattie Avatar answered Oct 16 '22 18:10

Dylan Beattie


It seems as though HTML elements do not contain a pointer back to their parent window, as it does for parentNode. Thus, this.window will return undefined when this is anything other than a window object.

The window object seems to be able to reference itself, perhaps because it is the only node high enough to "see" itself. Thus, window == window.window.window.window and so on.

The idiosyncrasies between browsers seem to do with how each implements the DOM structure, and in particular, how they interpret this at the top-level.

Seeing as how individual HTML elements can't reference their parent window with .window, I don't really see a point in ever using this.window, though I'd love to be proved wrong here.

If you're working on code that involves manipulating objects across two different windows, I would suggest assigning your new window to a variable, e.g. var newWin = window.open(...) and subsequently using this variable to reference new objects.

like image 27
Jeff Avatar answered Oct 16 '22 17:10

Jeff