Get javascript class name or typeof in parent constructor

前端 未结 2 619
遥遥无期
遥遥无期 2021-01-26 11:49

I have two classes in Javascript like this:

class Parent {
    constructor(){
        console.log(typeof this);
    }
}

class Child extends Parent {
    constru         


        
2条回答
  •  甜味超标
    2021-01-26 12:13

    this.constructor will return the constructor function with which the objet was created. You could access this.constructor.name if you need a string.

    class Parent {
        constructor(){
            console.log(this.constructor.name);
        }
    }
    
    class Child extends Parent {
        constructor(){
            super();
        }
    }
    
    new Child(); // Child
    new Parent(); // Parent

提交回复
热议问题