Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A clean way of checking whether an object is an instance of window.constructor

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.

like image 725
Witiko Avatar asked Jun 03 '11 15:06

Witiko


1 Answers

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

like image 65
lonesomeday Avatar answered Sep 21 '22 00:09

lonesomeday