首页 > 解决方案 > 在 ES6 的子超级方法中获取 js 类名

问题描述

我在 JS 中有一个父类,它具有一些属性,其中一些属性基于子类的类名:

父类.js

export default class ParentClass {

    constructor(className) {

        this.className = className;
        this.classNameLowerCase = className.toLowerCase();
    }
}

在子类中,我扩展了父类并super()用于构造函数调用,我将在其中传递子类的类名。

ChildClass.js

import ParentClass from  "./ParentClass.js";


class ChildClass extends ParentClass {

    constructor() {
        super("ChildClass");
    }
}

如您所见,子类称为ChildClass,我还将这个名称作为字符串传递给super(). 我更喜欢用函数获取子类的类名(不必重复我自己)。如果不使用super(),我可以使用this.constructor.name来获取类的名称,但是在super() this父类构造函数调用之前,不允许在内部,也不允许在任何地方使用。

如何让子类名称用作内部参数super()

标签: javascriptecmascript-6

解决方案


一种选择是将功能放入父构造函数中 - 如果没有className通过,请检查this.constructor.name

class ParentClass {
    constructor(className) {
        if (!className) {
            className = this.constructor.name;
        }
        this.className = className;
        this.classNameLowerCase = className.toLowerCase();
    }
}

class ChildClass extends ParentClass {
    constructor() {
        super();
    }
}

const c = new ChildClass();
console.log(c.className);


推荐阅读