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.
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.
-
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./questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript
– ncubica Commented Dec 8, 2012 at 1:51
1 Answer
Reset to default 6The 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