I have two classes in Javascript like this:
class Parent {
constructor(){
console.log(typeof this);
}
}
class Child extends Parent {
constructor(){
super();
}
}
In the Parent class, I would like to know what class instantiated it. However, typeof just returns object. Is there any other way to solve this?
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.