笔记整理:判断变量类型的方法
-
typeof
typeof 返回对象的类型,缺点是像Array、Math、Date、Reg、null等这些对象也全部返回object;
typeof 1 //number
typeof “” //string
typeof undefined //undefined
typeof [] //object
typeof null //object -
instanceof 判断变量属于哪种类型,缺点是无法识别原始类型;
(new Date()) instanceof Date //true
[] instanceof Array //true
/\d+/ instanceof RegExp //true
“” instanceof String //false -
constructor 通过变量点出constructor.name,constructor.name返回变量的具体类型,缺点是无法识别null和undefined,null和undefined没有构造函数;另外有原型时constructor.name失效;多重继承时constructor.name失效;
“2”.constructor.name //String
[].constructor.name //Array
new Date().constructor.name //Date
null.constructor.name //TypeErrorfunction father(){}
father.prototype={
name:“xx”,
value:function(){}
}
new father().constructor.name //Objectfunction a(){}
function b(){}
b.prototype=new a()// b继承a;
let c=new b();
c.constructor=a; // true
c.constructor.name; //“a”
c.constructor=b; //false -
Object.prototype.toString.call(obj) 检测对象的内部属性,无法识别自定义对象的具体类型;
Object.prototype.toString.call(new Date()) //[object Date]
console.log(Object.prototype.toString.call(/+d/)); //[object RegExp]
Object.prototype.toString.call(""); //[object String]
Object.prototype.toString.call(function(){}) //[object Function]function getData(){}
Object.prototype.toString.call(new getData()); //[object Object]