最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - A clean way of checking whether an object is an instance of window.constructor - Stack Overflow

programmeradmin5浏览0评论

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.

Share Improve this question asked Jun 3, 2011 at 15:39 WitikoWitiko 3,4174 gold badges27 silver badges44 bronze badges 1
  • 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
Add a ment  | 

1 Answer 1

Reset to default 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

发布评论

评论列表(0)

  1. 暂无评论