9

The title pretty much says it all. I need to check whether an object is an instance of the DOM:Window interface. window will pass the test, window.frames[xyz] as well, should the iframe exist.

The most intuitive way appears to be a simple instanceof check via object instanceof window.constructor. It's a sad state of affairs that there are browsers (like IE6), whose window.constructor equals to undefined.

What would you suggest? There are always hacky, ugly and toString dependant ways like /\[object.*window.*\]/i.test(object), but I would rather go for a simple, clean solution, if possible.

Witiko
  • 3,167
  • 3
  • 25
  • 43
  • You can find a good explanation of how to detect object in javascript and about the problems using each technique. worth the read... `http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript` – ncubica Dec 08 '12 at 01:51

1 Answers1

6

The window object has the unusual property window, which always points to the same window object. It would be very unlikely for any other object to replicate this behaviour, so you could use it as a fallback to the window.constructor test:

function isWindow(obj) {
    if (typeof(window.constructor) !== 'undefined') {
        return obj instanceof window.constructor;
    } else {
        return obj.window === obj;
    }
}

jsFiddle showing this behaviour

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • Nice, it indeed works in all the browsers I could throw it at (IE 7+, Firefox, Chrome). – Frédéric Hamidi Jun 03 '11 at 16:09
  • 3
    I found another inconsistency: `window.open() instanceof window.constructor` equals `false`. Seems like the DOM:Window interfaces of different DOM instances don't share the same pointer, which is quite unfortunate indeed. `obj.window === obj` is rather solid, but I was looking forward to offering a nice, standardized way to those browsers that'd support it. – Witiko Jun 03 '11 at 17:07
  • I tried to utilise the non-standardised, yet widely supported `Function.prototype.name` property: `window.constructor?(obj instanceof window.constructor || (obj.constructor instanceof Function && obj.constructor.name?obj.constructor.name === window.constructor.name:obj.window === obj)):obj.window === obj` – Witiko Jun 03 '11 at 17:59
  • 1
    Why is it that if `window.constructor` is `undefined`, the function checks if the object is an instance of it? Shouldn't `===` be `!==`? – Gust van de Wal Dec 10 '19 at 15:47
  • @GustvandeWal Yes, it should. Fixed. – lonesomeday Dec 10 '19 at 21:46