日期:2014-05-16  浏览次数:20412 次

JS对象类型的确定
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类型子类的实例,同样满足。比如
var o=[];
alert(o instanceof Array);//true
alert(o instanceof Object);//true
var f=function(){}
alert(f instanceof Function);//true
alert(f instanceof Object);//true


如果要判断一个对象是否为某个具体类(子类)的实例,可以看该对象的constructor属性。
var d=new Date();
alert(d instanceof Object);//true
alert(d.constructor==Object);//false
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);
        var d=new Date();
    	alert(Object.prototype.toString.apply(d));//[object Date]
    	var a=[];
    	alert(Object.prototype.toString.apply(a));//[object Array]


用于获得对象类型的工具方法
function getType(x){
	if(x==null){
		return "null";
	}
	var t= typeof x;
	if(t!="object"){
		return t;
	}
	var c=Object.prototype.toString.apply(x);
	c=c.substring(8,c.length-1);
	if(c!="Object"){
		return c;
	}
	if(x.constructor==Object){
		return c
	}
	if("classname" in x.prototype.constructor
			&& typeof x.prototype.constructor.classname=="string"){
		return x.constructor.prototype.classname;
	}
	return "<unknown type>";
}