typeof、instanceof、Object.prototype.toString.call()
当我们需要判断一个变量的类型时经常会用到typeof,但是当去判断一个引用数据类型对象时,它返回的永远是"object"。
这时候我们需要用到instanceof来判断某个对象是不是另一个对象的实例,instanceof运算符用来检测构造函数的prototype属性是否存在于参数object的原型链上。语法: object instanceof constructor
例如我们去判断一个数组
let arr = [];
console.log(typeof arr); // 打印 object
console.log(arr instanceof Array); // 打印 true
再比如我们去判断person是不是Person的实例
function Person(name) {
this.name = name;
}
let person = new Person();
console.log(typeof person); // 打印 object
console.log(person instanceof Person); // 打印true
instanceof可以在继承关系中用来判断一个实例是否属于它的父类型。
class Person {
constructor(name) {
this.name = name;
}
}
class BoyPerson extends Person{
constructor(name, age) {
super(name);
this.age = age;
}
}
let boy = new BoyPerson('xiaoming', 12);
console.log(boy instanceof BoyPerson); // 打印 true
console.log(boy instanceof Person); // 打印 true
Object.prototype.toString.call(property)也可以判断变量是属于那种内置类型。
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(“abc”);// "[object String]"
Object.prototype.toString.call(123);// "[object Number]"
Object.prototype.toString.call(true);// "[object Boolean]"
**函数类型**
Function fn(){
console.log(“test”);
}
Object.prototype.toString.call(fn); // "[object Function]"
**日期类型**
var date = new Date();
Object.prototype.toString.call(date); // "[object Date]"
**数组类型**
var arr = [1,2,3];
Object.prototype.toString.call(arr); // "[object Array]"
**正则表达式**
var reg = /[hbc]at/gi;
Object.prototype.toString.call(reg); // "[object RegExp]"
**自定义类型**
function Person(name, age) {
this.name = name;
this.age = age;
}
var person = new Person("Rose", 18);
Object.prototype.toString.call(arr); // "[object Object]"
总结:
- 如果仅判断基本数据类型,typeof相对简单。 使用上typeof property === 'number'
- 如果要判断是对象、数组、日期、Function、RegExp,可以使用arr instanceof Array、Object.prototype.toString.call(obj) === '[object, Object]'来判断。
- 如果判断某变量是某构造函数实例,使用instanceof.