您的位置:首页 > Web前端 > JavaScript

js面向对象编程:如何检测对象类型

2014-07-14 11:09 441 查看
 在js中检测对象类型主要有三种,typeof,instanceof,constructor,这几种都可以检测对象的类型,但又有一定的区别。另外还可以使用jQuery来检测类型

  1使用typeof检测对象类型。

   typeo作为最常用的检测类型的方法,返回字符串类型,具体使用如下:

function testType(value)
{
var str=typeof(value);
//  alert(str);
switch(str)
{
case 'undefined': // undefined类型
case 'object' : // null类型,任意内置对象,数组
case 'boolean' : // true,false类型
case 'string' : // string字符串类型
case 'function':  //任意函数
case 'number': //任意的数值类型,包含NaN
}

}


可以看到,对于最基本的类型可以测试出类型,但对于其他的,包括日期,数组等大多都返回object类型,而且null也返回的是object类型,也就是没有办法知道确切的类型。

另一种改进的检测方法,是使用,默认的ToString,继承自object,可以返回类型信息

function classof(o) {
if (o === null) return "Null";
if (o === undefined) return "Undefined";
return Object.prototype.toString.call(o).slice(8,-1);
}
function testType(value)
{
var str=classof(value);//typeof(value);
alert(str);
switch(str)
{
case 'undefined': // undefined类型
case 'object' : // 对象
case 'Boolean' : // true,false类型
case 'String' : // string字符串类型
case 'Function':  //任意函数
case 'Number': //任意的数值类型,包含NaN
case 'Date'	://日期
case 'Array'	://数组
case 'RegExp'	://正则

}

}


可以看到改进了一部分,但object类型还是有很大一部分。

2使用instanceof检测对象类型

   对于typeof检测为object类型的可以使用instanceof进一步检测具体的类型。instanceof实际上检测的对象的原型。

  可以检测变量是不是某个对象的实例,返回bool值。

例如:

var value=new Date();
var isdate= value instanceof Date
alert(isdate);

[b]3使用constructor检测对象类型检测对象类型[/b]

  constructor相当于检测构造函数,返回的是一个函数

例如:

function testconstructor(value)
{
var str=value.constructor;
switch(value.constructor)
{
case Number: //	数值类型
break;
}
//  alert(str);
}


如果需要检测一个对象的确切类型,可以综合使用这三种方法

例如:

function type(o) {
var t, c, n;  // type, class, name
// 是null类型:
if (o === null) return "null";
// 是数值中的特殊类型: NaN :
if (o !== o) return "nan";
// 使用 typeof 检测除去 "object"类型为的其他类型.
if ((t = typeof o) !== "object") return t;
// typeof检测为"object"类型,则进一步检测
// 可以检测出大部分内置类型
if ((c = classof(o)) !== "Object") return c;
// classof(o)返回为"Object"时,检测constructor
if (o.constructor && typeof o.constructor === "function" &&
(n = o.constructor.getName())) return n;
// 无法识别的其他类型,默认为"Object"
return "Object";
}
function classof(o) {
return Object.prototype.toString.call(o).slice(8,-1);
};

// 返回function的名称,可能为""或者 null
Function.prototype.getName = function() {
if ("name" in this) return this.name;
return this.name = this.toString().match(/function\s*([^(]*)\(/)[1];
};

还可以使用jQuery来检测类型,常用的方法如下:

jQuery.isArray(obj)测试对象是否为数组。

jQuery.isFunction(obj) 测试对象是否为函数。

jQuery.isEmptyObject(obj)  jQuery 1.4 中,这个方法既检测对象本身的属性,也检测从原型继承的属性(因此没有使用hasOwnProperty)。

jQuery.isPlainObject(obj) 测试对象是否是纯粹的对象(通过 "{}" 或者 "new Object" 创建的)。

jQuery.isWindow(obj)  测试对象是否是窗口(有可能是Frame)。


jQuery.type(obj)  检测obj的数据类型。

jQuery.isNumeric(value) 确定它的参数是否是一个数字,包含16进制数

 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: