js之检测对象类型
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>检测数据类型</title> </head> <body> <script> /*检测字符串、数值、布尔值、undefined*/ /*神器之 typeof*/ var s="lily", b=true, i=22, u, n=null, o=new Object(); console.log(typeof s); console.log(typeof b); console.log(typeof i); console.log(typeof u); console.log(typeof n); console.log(typeof o); /*ECMA-262规定任何在内部实现[[call]]方法的对象都应该在应用typeof操作符时返回"function"*/ /*检测引用类型变量*/ /*神器之 instanceof*/ /*result=variable instanceof constructor*/ var person=new Object, colors=new Array, pattern=new RegExp; console.log(person instanceof Object); console.log(colors instanceof Array); console.log(pattern instanceof RegExp); /*神器之 constructor*/ console.log(person.constructor); console.log(colors.constructor); console.log(pattern.constructor); /*注意: constructor 在类继承时会出错 eg, function A(){}; function B(){}; A.prototype = new B(); //A继承自B var aObj = new A(); alert(aobj.constructor === B) -----------> true; alert(aobj.constructor === A) -----------> false; 而instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true: alert(aobj instanceof B) ----------------> true; alert(aobj instanceof B) ----------------> true; 言归正传,解决construtor的问题通常是让对象的constructor手动指向自己: aobj.constructor = A; //将自己的类赋值给对象的constructor属性 alert(aobj.constructor === A) -----------> true; alert(aobj.constructor === B) -----------> false; //基类不会报true了; */ /*神器之 prototype*/ var a=Object.prototype.toString.call(person), b=Object.prototype.toString.call(colors), c=Object.prototype.toString.call(pattern); console.log(a.split("").slice(8,-1).join("")); console.log(b.split("").slice(8,-1).join("")); console.log(c.split("").slice(8,-1).join("")); </script> </body> </html>
检测类型方法总结:
1 typeof
2 instanceof
3 constructor
4 Object.prototype,toString.call()
放下过去,才能迎接未来!
未来的每一天我都要过的精彩!