开发者

JavaScript this.window not equal to window

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.


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');


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.


Works here...

http://jsfiddle.net/rygar/DQYdk/


Because this equals window in global context.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜