js中判断一个类型大体上有四种常用的方式
- typeof
- constructor
- instanceof
- object.property.toString.call
typeof
对于基本类型,除 null 以外,均可以返回正确的结果。对于引用类型,除 function 以外,一律返回 object 类型typeof ''; // string 有效typeof 1; // number 有效typeof Symbol(); // symbol 有效typeof BigInt(9007199254740991)//'bigint' 有效typeof true; //boolean 有效typeof undefined; //undefined 有效typeof new Function(); // function 有效typeof null; //object 无效typeof [] ; //object 无效typeof new Date(); //object 无效typeof new RegExp(); //object 无效
constructor
constructor 是用于标识对象类型的,效果等同于instanceof 不过一般认为instanceof 是更可靠的方式,如下:
虽然,原型有被重写的可能,但我们任然可以通过constructor 来判断对象类型,null和undefined不能通过此种方式来判断 ```javascript ‘’.constructor === String//true Number(1).constructor === Number//true true.constructor === Boolean//true Symbol().constructor === Symbol//true BigInt(9007199254740991).constructor === BigInt//truefunction Person() {}Person.prototype = {name: "Nicholas",age: 29,job: "Software Engineer",sayName() {console.log(this.name);}};const friend = new Person()//当原型对象被重写后,constructor就不能指向正确的构造函数friend instanceof Person //truefriend.constructor === Person//falsefriend.constructor === Object //true 指向了一个新的object
new Function().constructor === Function//true new Date().constructor === Date //true [].constructor === Array//true new Error().constructor === Error//true new RegExp().constructor === RegExp
<a name="mIZGX"></a>### instanceof用于判断一个实例是否属于某种类型。语法是 `_object_ instanceof _constructor_`_ _```javascript[] instanceof Array //truenew Date() instanceof Date //truenew RegExp() instanceof RegExp //truenew Error() instanceof Error //truefunction Person(){};new Person() instanceof Person; //true//检查的是原型链 ,所以下面的也是true[] instanceof Object; // truenew Date() instanceof Object;// truenew Person instanceof Object;// true
instanceof是更可靠的用来识别对象类型的方式。它能正确的辨别内置的引用类型和自定义类型
Object.prototype.toString.call
对于 Object 对象,直接调用 toString() 就能返回 [object Object]。
这种方式是最全面的,能同时判断引用类型和基本数据类型和null/undefined这种特殊的类型
aa = {a:2,b:3}
aa.toString()//'[object Object]'
Object.prototype.toString.call('') ; // [object String]
Object.prototype.toString.call(1) ; // [object Number]
Object.prototype.toString.call(true) ; // [object Boolean]
Object.prototype.toString.call(Symbol()); //[object Symbol]
Object.prototype.toString.call(undefined) ; // [object Undefined]
Object.prototype.toString.call(null) ; // [object Null]
Object.prototype.toString.call(new Function()) ; // [object Function]
Object.prototype.toString.call(new Date()) ; // [object Date]
Object.prototype.toString.call([]) ; // [object Array]
Object.prototype.toString.call(new RegExp()) ; // [object RegExp]
Object.prototype.toString.call(new Error()) ; // [object Error]
Object.prototype.toString.call(document) ; // [object HTMLDocument]
Object.prototype.toString.call(window) ; //[object global] window 是全局对象 global 的引用
