Skip to content Skip to sidebar Skip to footer

Get Javascript Class Name Or Typeof In Parent Constructor

I have two classes in Javascript like this: class Parent { constructor(){ console.log(typeof this); } } class Child extends Parent { constructor(){ sup

Solution 1:

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

classParent {
    constructor(){
        console.log(this.constructor.name);
    }
}

classChildextendsParent {
    constructor(){
        super();
    }
}

newChild(); // ChildnewParent(); // Parent

Solution 2:

Since you are using ES6 classes, new.target is what you are looking for. But notice that it's usually an antipattern to let a constructor's behaviour depend on particular child classes.

Post a Comment for "Get Javascript Class Name Or Typeof In Parent Constructor"