javascript - ES6 从现有实例实例化派生类
问题描述
考虑以下场景:
class A {
constructor() {
this.A = 'A';
}
createB() {
//Create a B instance from this current instance
}
}
class B extends A {
constructor() {
super();
this.B = 'B';
}
}
var base = new A();
var derived = new B();
base.A = 'C';
// Create a B instance from A so that
// a new A isn't instantiated and
// fromInstance.A === 'C'
var fromInstance = base.createB();
我希望能够创建一个实例B
而不必创建一个新的实例A
,而是使用现有的A
实例。
我的目标是能够B
通过调用内部的函数来生成实例A
,但也允许B
直接创建实例并处理构造默认值A
。
B
当扩展A
并需要super()
调用时,我怎样才能实现这样的目标?
解决方案
不确定这正是您想要的,但它适用于您的示例:
class A {
constructor() {
this.A = 'A';
}
}
class B extends A {
constructor() {
super();
this.B = 'B';
}
}
var base = new A();
var derived = new B();
base.A = 'C';
// Create a B instance from A so that
// a new A isn't instantiated and
// fromInstance.A === 'C'
var fromInstance = new B();
Object.assign(fromInstance, base);
console.log(fromInstance);
这是一个替代解决方案。它实际上在 C# 和 Java 中很常见,但是由于 JS 没有方法重载,因此与上述解决方案相比,这有点麻烦并且不太好:
class A {
constructor(source) {
if(source){
//use properties/stuff from source
this.A=source.A;
}
else{
//only perform initialization if source is not provided
this.A = 'A';
}
}
}
class B extends A {
constructor(source) {
super(source);
this.B = 'B';
}
}
var base = new A();
var derived = new B();
base.A = 'C';
// Create a B instance from A so that
// a new A isn't instantiated and
// fromInstance.A === 'C'
var fromInstance = new B(base);
console.log(fromInstance);
基本上,构造函数有两个版本,一个创建一个全新的对象,一个几乎复制一个旧对象。
我认为有一点误解,B
根据定义,每个实例都是 的实例A
,无论您做什么。如果您想super
被调用,您正在调用 的构造函数A
,从而“实例化” A
。
推荐阅读
- python - 无法在 Python Flink 1.11.X 上使用某些聚合函数(求和或计数)
- angularjs - 没有项目支持“服务”目标。卡住并且无法在我的本地主机上运行 Angular 项目
- web - 如何从用户代理检测 Windows 11?
- python - 如何在 seaborn - seaborn zorder 的 violinplot 前显示箱线图?
- git - 什么是在 Git 中标记不是提交的对象?
- android - IOS 等视频中的 Android Camera 2 人像模式
- reactjs - 如何搜索折线附近的所有点?
- python-3.x - 如何阻止 MDSwiper 重叠 KivyMD 底栏应用程序
- mongodb - Mongodb服务器没有运行
- python - python request.get API 参数、标头、参数 - 混淆