为什么要比较“ .constructor”?两个窗口的属性不可靠? [英] Why is comparing the ".constructor" property of two windows unreliable?

查看:71
本文介绍了为什么要比较“ .constructor”?两个窗口的属性不可靠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么以下内容无法正常工作。我想检查一个物体是否是窗户。我当时认为检查当前窗口和另一个窗口的构造函数会起作用。

I'm trying to understand why the following is not working as I would think it does. I'd like to check whether an object is a window. I was thinking that checking the constructors of the current window and another window would work.

因此,首先创建另一个窗口:

So, first creating another window:

var popup = window.open('', '', '');

然后检查:

popup.constructor === window.constructor;

但是由于某些原因,结果在浏览器中会有所不同:

But for some reason the results vary among browsers:


  • IE7:返回 true

    • 但这仅仅是因为 .constructor ===未定义

    • IE7: Returns true
      • But that's simply because .constructor === undefined

      • 尽管在两种情况下 .constructor === DOMWindow -但是 DOMWindow 不能像这样直接访问

      • Though in both cases .constructor === DOMWindow - but DOMWindow is not accessible directly like this

      • 尽管在两种情况下 .constructor === Object

      • Though in both cases .constructor === Object

      • 尽管在两种情况下 .constructor === Window

      • Though in both cases .constructor === Window

      为什么这不可靠且无法正常工作? jQuery只是在窗口中检查 setInterval ,但是我想创建一个更强大的函数来检查对象是否是窗口。

      Why isn't this reliable and working correctly? jQuery simply checks for "setInterval" in window, but I'd like to create a more robust function for checking whether an object is a window.

      推荐答案

      每个单独的窗口是解释器的单独全局上下文(是的,我忽略了IE7目前)。当您考虑 instanceof 时,您的问题就很清楚了:

      Every separate window is a separate global context for the interpreter (and yes I'm ignoring IE7 for the moment). Your issue really becomes clear when you think about instanceof:

      if (something instanceof Array) { ... }
      

      当某物是一个值时,就会出现问题是在单独的上下文中构建的,例如iframe。每个窗口都有它自己的 Array构造函数的副本,因此,即使一个对象可能是Array实例,也不是同一构造函数的实例。

      The problems with that occur when "something" is a value that was constructed in a separate context, like an iframe for example. Each window has it's very own copy of the "Array" constructor, so even though an object may be an Array instance, it's not an instance of the same constructor function.

      我怀疑IE7行为与我认为的其他一些怪异有关,例如 window.window 不等于窗口。就像,其中之一实际上是对内部事物的引用。 (也许 window 不等于 window.self ,尽管它们的行为相同。我不投资考虑IE7的大量哲学思考时间。)

      I suspect that the IE7 behavior is related to some other weirdness that I think is something like window.window being not equal to window. Like, one of them is in fact a reference to something internal. (Maybe it's window not being equal to window.self even though they otherwise behave identically. I don't invest a lot of philosophical thought time in contemplating IE7.)

      这篇关于为什么要比较“ .constructor”?两个窗口的属性不可靠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆