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 toS开发者_Go百科tring dependant ways like /\[object.*window.*\]/i.test(object), but I would rather go for a simple, clean solution, if possible.
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
加载中,请稍侯......
精彩评论