[JS学习笔记]如何判断对象属于哪个类?

76 阅读1分钟

判断对象属于哪个类的方法

class Person{
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
}
class GoodPerson extends Person{
    constructor(name,age,hobby){
        super(name,age);
        this.hobby = hobby;
    }
}
class Dog{
    constructor(name,type){
        this.name = name;
        this.type = type;
    }
}
let Missy =  new Person("Missy",22);
let Evan = new GoodPerson("Evan",20,"C++");
  1. instanceof

    原理是:在对象的原型链上找构造函数的prototype,如果涉及到继承,继承的构造函数也会判断为true

     console.log(Missy instanceof Person); //true
     console.log(Evan instanceof Person);//true
    
  2. constructor

    构造函数可以修改,所以不是很准确

     console.log(Missy.constructor); //person
     Missy.constructor = Dog;
     console.log(Missy.constructor); //dog
    
  3. Object.prototype.toString.call()

    内置对象可以判断出具体的类,但是无法区分自定义对象类型。

    Object.prototype.toString是原型链上的方法,但可能被重写。所以用.call()来调用。

    .call(obj)使得this指向obj,否则toString的this将始终指向prototype

    console.log(Object.prototype.toString.call(2)); //Number
    console.log(Object.prototype.toString.call(Missy)); //Object