标签:
JS为弱类型语言,所以类型识别对JS而言尤为重要,JS中常用的类型识别方法有4种:typeof、Object.prototype.toString、constructor和instanceof。
(1)typeof可以识别标准类型(Null除外),不能识别具体的对象类型(Function除外),举例如下:
1 console.log(typeof("tom")); //"string" 2 console.log(typeof(12)); //"number" 3 console.log(typeof(true)); //"boolean" 4 console.log(typeof(undefined)); //"undefined" 5 console.log(typeof(null)); //"objectl" null被识别为object 6 console.log(typeof({name:"yxz"})); //"object" 7 console.log(typeof(function(){})); // "function"
(2)Object.prototype.toString可以识别标准类型以及内置对象类型,不能识别自定义类型,举例如下:
先封装一个函数实现Object.prototype.toString功能。
1 function type(obj){ 2 return Object.prototype.toString.call(obj).slice(8,-1).toLowerCase(); 3 } 4 console.log(type(1));//"number" 5 console.log(type("abc"));//"string" 6 console.log(type(true));//"boolean" 7 console.log(type(undefined));//"undefined" 8 console.log(type(null));//"null" 9 console.log(type({}));//"object" 10 console.log(type(new Date));//"date" 11 console.log(type(function(){}));//"funciton" 12 console.log(type([]));//"array" 13 function Point(x,y){ 14 this.x = x; 15 this.y = y; 16 } 17 console.log(type(new Point(1,2)));//"object" 自定义类型不能识别
(3)constructor是对象原型上面的一个属性,它指向构造器本身,constructor可以识别标准类型(Undefined/Null除外),可以识别内置对象类型,可以识别自定义对象类型,举例如下:
1 //标准类型 2 console.log("tom".constructor == String);//true 3 console.log((1).constructor == Number);//true 4 console.log(true.constructor == Boolean);//true 5 console.log({}.constructor == Object);//true 6 //内置类型对象 7 console.log([].constructor == Array);//true 8 //自定义对象 9 function Person(name){ 10 this.name = name; 11 } 12 console.log(new Person("tom").constructor == Person);//true
(4)instanceof可以识别内置对象类型,不能识别原始类型,可以识别自定义对象类型,举例如下:
1 //识别内置对象类型 2 console.log([] instanceof Array);//true 3 //不能识别原始类型 4 console.log(1 instanceof Number);//false 5 console.log("tom" instanceof String);//false 6 //能识别自定义对象类型及父子类型 7 function Point(x,y){ 8 this.x = x; 9 this.y = y; 10 } 11 function Circle(x,y,r){ 12 Point.call(this,x,y); 13 this.radius = r; 14 } 15 Circle.prototype = new Point(); 16 Circle.prototype.constructor = Circle; 17 var c = new Circle(1,1,2); 18 console.log(c instanceof Circle);//true 19 console.log(c instanceof Point);//true
标签:
原文地址:http://www.cnblogs.com/yxz-turing/p/4736248.html