JavaScript中基本类型包含Undefined、Null、Boolean、Number、String以及Object引用类型。
基本类型可以通过typeof来进行检测,对象类型可以通过instanceof来检测。
但这两检测方式本身存在大量的陷阱,因此需要进行兼容处理。

对于typeof,只能识别出undefined、object、boolean、number、string、function这6种数据类型,无法识别Null等细分的对象类型。
typeof本身存在的陷阱:
typeof null; 结果为"object"
typeof document.all; 在IE外的其他现代浏览器下会返回"undefined",但实际上是可用的(该方法被大量用作判断IE,因此浏览器厂商也有对应规则)。
typeof document.childNodes; 在safari下结果为"function"
typeof document.createElement('embed'); 在firefox下结果为"function"
typeof document.createElement('object'); 在firefox下结果为"function"
typeof document.createElement('applet'); 在firefox下结果为"function"
typeof window.alert; 在IE678下为"object",
IE678下有个HACK技巧:window==document 在IE678下为true(而document==window为false)。

对于typeof,在IE下判断ActiveX对象的方法时还会返回unknow的情况,例如:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <style rel="stylesheet" type="text/css">
 6 </style>
 7 <script>
 8 window.onload=function(){
 9     if(window.ActiveXObject){
10         var xhr=new ActiveXObject("Msxml2.XMLHTTP");
11         document.body.innerHTML=(typeof xhr.abort);
12     }
13 }
14 </script>
15 </head>
16 <body><div class="show">HELLO</div></body>
17 </html>
typeof在IE下判断ActiveX方法的时候会返回unknow

相关文章: