Go to the topic.
First look at jQuery's $. isWindow function:
Copy codeThe Code is as follows: function isWin (obj ){
Return obj & typeof obj === 'object' & 'setinterval' in obj;
}
This function is very scientific. It mainly checks whether the target object has the setInterval attribute.
However, the problem is that, in the absence of conventions, it may not be too reliable, for example:
Copy codeThe Code is as follows: var o = {xx: 'oo '};
O ['setinterval'] = true;
Console. log (isWin (o); // true
In the preceding example, the property setInterval is successfully added to the object literal.
In fact, any non-null Object can be so disguised, such as Arrays:
Copy codeThe Code is as follows: var arr = [1, 2, 3];
Arr ['setinterval'] = true;
Console. log (isWin (arr); // true
Compared with the attribute check above, a more appropriate method is to use the toString function of the object to judge:
Copy codeThe Code is as follows: function isWin (obj ){
Return Object. prototype. toString. call (obj) = '[object Window]'
}
The above functions are properly implemented in the standard browser, but at the same time bring about new compatibility problems:
Copy codeThe Code is as follows: // The result in the ie6-8
Object. prototype. toString. call (window) ===' [object Window] '; // false
Object. prototype. toString. call (window) ===' [object Object] '; // true
// Chrome
Object. prototype. toString. call (window) ===' [object global] '; // true
// Safari
Object. prototype. toString. call (window) ===' [object DOMWindow] '; // true
Sure enough, the main problem is from the evil ie. Fortunately, there is no such thing as a path, which reminds me of a spiritual event in ie:
Copy codeThe Code is as follows: // The following two lines: Believe it or not?
Console. log (window = document); // true
Console. log (document = window); // false
Here, I think the final solution has come out:
Copy codeThe Code is as follows: function isWin (obj ){
Return/Window | global/. test ({}. toString. call (obj) | obj?#obj.document&obj.doc ument! = Obj;
}