js中判断一个数据是什么类

由判断一个对象属于哪个类想到的

有时候,我们会有这样的需求。判断我们手中的某个数据是属于哪一个类,哪一种数据类型。通常有以下几种方式:
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+"]";
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值