我在JS中有一个父类,它有一些属性,其中有些是基于子类的类名的:
ParentClass.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()
中的参数
发布于 2019-08-01 08:51:25
一种选择是将该功能放入父构造函数--如果没有传递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);
https://stackoverflow.com/questions/57305125
复制相似问题