Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's .isWindow method?

I was trying to understand what I could from jQuery's animation functions, but ended up running into all sorts of internal functions I didn't understand, and ultimately landed on isWindow. The code for isWindow checks to see if an object has the property setInterval, and returns false otherwise.

Of course, any object could have the property setInterval without being the window, and although it would almost have to be a deliberate attempt to sabotage jQuery's functionality to have an object with that exact property name, I can imagine some reasonable cases where it could be unintentional.

Is there not a better way to check if an object is a window object? Couldn't they use something along the lines of

obj.setInterval && obj.setInterval.toString() == 'function setIternval(){ [native code] }

I know the return of toString of an internal function isn't going to be standard across all browsers, but the writers of jQuery seem to have a great understanding of these cross-browser differences. I'm also aware that this isn't a fool-proof method either, as someone could easily override the toString method to return that same string, but this would still prevent the problem of having an object mistaken for a window.

I wouldn't ask if I thought that isWindow was only used on internal objects by jQuery, but it was part of isPlainObject, which is used in .extend, which can be used on external objects.

like image 523
mowwwalker Avatar asked Mar 06 '12 00:03

mowwwalker


1 Answers

What about:

function isWindow(obj) {
  var toString = Object.prototype.toString.call(obj);
  return toString == '[object global]' || toString == '[object Window]' || toString == '[object DOMWindow]';
}

Seems to work in Chrome, Firefox, Opera, IE and Safari (Newest versions)

like image 59
Saebekassebil Avatar answered Oct 06 '22 06:10

Saebekassebil