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

Get javascript class name or typeof in parent constructor

本文关键字:类型 javascript 获取 构造函数      更新时间:2023-09-26

我在Javascript中有两个这样的类:

class Parent {
    constructor(){
        console.log(typeof this);
    }
}
class Child extends Parent {
    constructor(){
        super();
    }
}
在Parent类中,我想知道是哪个类实例化了它。然而,typeof只是返回object。还有其他解决办法吗?

this.constructor将返回创建对象时使用的构造函数。如果需要字符串,可以访问this.constructor.name

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

由于您正在使用ES6类,new.target是您正在寻找的。但是请注意,让构造函数的行为依赖于特定的子类通常是一种反模式。