javascript - 使用类的构造函数初始化另一个类
问题描述
在重构一段代码时,我遇到了一个我想用通用类替换的类。因此,它应该具有几乎相同的功能,但根据“类型”参数。
为了确保向后兼容性,我不想只创建一个新类,而是保留旧类的初始化。
但是我不确定如何在 JavaScript 中实现这个结构:
class Generic {
constructor(type, data) {
this.type = type;
this.data = data;
}
action() {
switch(this.type) {
// Does things dynamically, depending on `this.type`
case 'old': return `old: ${this.data}`;
default: return this.data;
}
}
}
class Old {
constructor(data) {
// I want this to be equivalent to:
// new Generic('old', data);
}
}
// So this should work seamlessly
const foo = new Old('Hello');
const output = foo.action();
console.log(output);
解决方案
您可以扩展通用:
class Old extends Generic {
constructor() {
super("old");
}
}
推荐阅读
- apache-spark - 增加 yarn-site.xml 中的 yarn.scheduler.maximum-allocation-mb 值
- c# - 通过正则表达式查找所有匹配的字符串
- r - 行中的条件标签
- clojure - 构建用户数据和通过应用函数关联它们的函数
- lua - 为什么我的闪光激光无法杀死 Roblox 中的玩家?
- python - Python:在有小数点的情况下使用点使每个句子换行
- python - 根据值从一组列中选择一个值并使用该值创建新列?
- c# - 按下拉列表对转发器值进行排序
- reactjs - 使用解构赋值结果未定义
- django - 在仅接受 yahoo、gmail 和 Outlook 的电子邮件中引发验证错误