javascript - 在 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()
?
解决方案
一种选择是将功能放入父构造函数中 - 如果没有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);
推荐阅读
- java - 如何运行与 Firebase 连接的方法时遇到问题的代码?
- c++ - 如何逐行读取文本文件中的字符串?
- node.js - 什么是无法在 node.js 中获取未定义或空引用的属性“应用”?
- android - 一个平均 Firebase 活跃用户指标(DAU、WAU、MAU)应该是什么?
- javascript - 如何使我的复选框过滤器具有包容性,而不是独占性
- php - 将 GZipStream 发布到 PHP 未能放气
- java - 使用带有jpa的spring mvc将数组转换为映射
- c - C - 如何添加三个数字?
- mysql - 对连接结果进行排序和分组?
- cross-platform - 如果在不同语言/架构的相同输入上运行,protobuf 会生成按位完美副本吗?