js 检测数据类型常用的方法:
typeof() 返回某个字符串
- undefined
- boolean
- string
- number
- object
- function
constructor 判断对象的类型
[].constructor==Array
/123/.constructor==RegExp
instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型
[] instanceof Array => true
[] instanceof Object => true
[] instanceof Date => false
Object.prototype.toString() 返回对象的字符串表示
为什么要使用Object.prototype.toString.call() 来检测变量类型呢?
因为 Array,Boolean,Number等都是Object的实例,如:Array instanceof Object 结果为true ,可以验证
Array,Boolean等都复写了toString的原型方法,在调用[].toString() 实际调用的是 Array.prototype.toString(),
如: 先 delete Array.prototype.toString,再调用[].toString() 则调用的是 Object.prototype.toString()方法
所以: 可以使用Object.prototype.toString.call()
讲解:
//定义两个构造函数(类)
function Person() {
};
function Student() {
};
//实例化
var p = new Person(),
s = new Student()
;
//在Object原型上添加show方法
Object.prototype.show = function () {
console.log("调用Object原型的show方法");
// 通过call()传递的对象,this指向也不一样,下面判断this的指向
console.log("是否是Person的实例",this===p,this instanceof Person)
console.log("是否是Student的实例",this===s,this instanceof Student)
};
//覆盖Object原型的show方法
Person.prototype.show = function () {
console.log("person")
};
Student.prototype.show = function () {
console.log("student")
};
//判断自定义的两个类是否是Object的实例
console.log(Person instanceof Object);
console.log(Student instanceof Object);
// 调用Object原型的方法
Object.prototype.show.call(p);
Object.prototype.show.call(s);
//调用自身实例原型的方法
p.show();
s.show();
所以:Object.prototype.toString.call(thisObj) 可以 判断数据类型
类型判断的函数的封装:
function typeOf(obj) {
var typeList = {
'[object Boolean]' : 'boolean',
'[object Number]' : 'number',
'[object String]' : 'string',
'[object Function]' : 'function',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object RegExp]' : 'regExp',
'[object Undefined]': 'undefined',
'[object Null]' : 'null',
'[object Object]' : 'object'
};
return typeList [Object.prototype.toString.call(obj)];
}