JS对象类型的确定

来源:互联网 发布:淘宝上买格力空调 编辑:程序博客网 时间:2024/05/19 15:20
JS是松散类型的语言,这一点JS的对象表现得尤为突出。那么如何来确定JS对象的具体类型呢? 

首先,我们可以使用typeof运算符确定其基本类型(number,object,function,undefined)。如果typeof运算符返回object我们再使用instanceof来确定该对象是否属于某个具体类型。 

注意:typeof null得到object,而typeof undefined得到undefined,typeof 数组对象得到object,typeof 函数得到function。 

o instanceof Type:判断对象o是否属于Type类型,如果o是Type类型子类的实例,同样满足。比如 
Js代码  收藏代码
  1. var o=[];  
  2. alert(o instanceof Array);//true  
  3. alert(o instanceof Object);//true  
  4. var f=function(){}  
  5. alert(f instanceof Function);//true  
  6. alert(f instanceof Object);//true  


如果要判断一个对象是否为某个具体类(子类)的实例,可以看该对象的constructor属性。 
Js代码  收藏代码
  1. var d=new Date();  
  2. alert(d instanceof Object);//true  
  3. alert(d.constructor==Object);//false  
  4. alert(d.constructor==Date);//true  


使用instanceof和constructor进行类型判断的缺点就是:你只能根据已经知道的类进行测试对象,而无法检查位置的对象。Object定义的默认的toString()方法的一个有趣现象在于它会揭示关于对象类型的信息。ECMAScript规范要求这个默认的toString()方法总是返回形式如下的一个字符串: 
[object class] 
class是对象的内部类型,通常和该对象的构造函数的名字相对应。例如,数组对象的class是Array,函数的class是Function,Date对象的class是Date,Math对象的class是Math。对于用户自定义的类型,class是Object,客户端的JS对象的class可能是Window、Document、Form等…… 

但是大多数类覆盖掉了默认的toString方法,需要Object.prototype中显示的调用默认函数,并且使用apply()所感兴趣的对象上调用: 
Object.prototype.toString.apply(o); 
Js代码  收藏代码
  1.    var d=new Date();  
  2. alert(Object.prototype.toString.apply(d));//[object Date]  
  3. var a=[];  
  4. alert(Object.prototype.toString.apply(a));//[object Array]  


用于获得对象类型的工具方法 
Js代码  收藏代码
  1. function getType(x){  
  2.     if(x==null){  
  3.         return "null";  
  4.     }  
  5.     var t= typeof x;  
  6.     if(t!="object"){  
  7.         return t;  
  8.     }  
  9.     var c=Object.prototype.toString.apply(x);  
  10.     c=c.substring(8,c.length-1);  
  11.     if(c!="Object"){  
  12.         return c;  
  13.     }  
  14.     if(x.constructor==Object){  
  15.         return c  
  16.     }  
  17.     if("classname" in x.prototype.constructor  
  18.             && typeof x.prototype.constructor.classname=="string"){  
  19.         return x.constructor.prototype.classname;  
  20.     }  
  21.     return "<unknown type>";  
  22. }  

0 0