简体   繁体   English

在父构造函数中获取javascript类名或typeof

[英]Get javascript class name or typeof in parent constructor

I have two classes in Javascript like this:我在 Javascript 中有两个类,如下所示:

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.在 Parent 类中,我想知道是哪个类实例化了它。 However, typeof just returns object.然而,typeof 只返回对象。 Is there any other way to solve this?有没有其他方法可以解决这个问题?

this.constructor will return the constructor function with which the objet was created. this.constructor将返回创建对象的构造函数。 You could access this.constructor.name if you need a string.如果需要字符串,可以访问this.constructor.name

 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.由于您使用的是 ES6 类,因此new.target就是您要查找的内容。 But notice that it's usually an antipattern to let a constructor's behaviour depend on particular child classes.但是请注意,让构造函数的行为依赖于特定的子类通常是一种反模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM