由判断一个对象属于哪个类想到的
有时候,我们会有这样的需求。判断我们手中的某个数据是属于哪一个类,哪一种数据类型。通常有以下几种方式:
1.typeof()
- var a = “A”; typeof(a) == “string” //true
- var b = 1; typeof(b) == “number” //true
- var d = []; typeof(d) == “object” //true
- var e = null; typeof(e) == “object” //true
- var f = undefined; typeof(f) == “undefined” //true
- 可以看到,typeof()只有判断基础数据类型的功能,当一些非基础数据类型,例如Date,RegExp等,均是对象,并且typeof返回的是一个字符串。
2.instanceof()
在判断对象的时候,我们可以使用instanceof,例如 [] instanceof Array //true;可以看到instanceof可以判断非基础的数据类型
- [] instanceof Array //true;
- new Date() instanceof Date //true;
- new Date() instanceof Object //true;
- 看出来,因为Object是所有对象的基类,所以所有的对象instanceof Object都是true;
3.instanceof()的原理
给出如下示例:
function Person(name, age){
this.name = name;
this.age = age;
}
function Student(score){
this.score = score;
}
Student.prototype = new Person('李明',22);
var s = new Student(99);
console.log(s instanceof Student); //true
console.log(s instanceof Person); //true
console.log(s instanceof Object); //true
我们看到s是Student的实例,Student原型继承Person;
它的原型链结构为
s.__proto__ == Student.prototype;
Student.prototype == new Person();
Student.proptype.__proro__ == Person.prototype;
所以instanceof的原理是看instanceof右边的对象指向的原型对象是否存在于左边对象的原型链之中
4.Object.prototype.toString.call();
- Object.prototype.toString.call([]) === “[object Array]” //true
- Object.prototype.toString.call(new Date()) === “[object Date]” //true
- 因此我们可以写一个函数来判断:
function is(obj, type){
var objType = Object.prototype.toString.call(obj);
return objType == "[object "+type+"]";
};