是否可以使用类的现有实例来创建扩展子类的新对象?
在下面的示例中,我有一个 Rectangle
对象 r
。我想创建一个新的 CompanyRectangle
对象 cr
,它以 Rectangle 的相同属性和方法开始,然后在其之上添加更多内容。
下面的示例有效,但所有属性都必须显式复制到 CompanyRectangle
构造函数中。是否可以通过自动复制所有属性的方式来做到这一点?
class Rectangle {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
update() {
// Has a bunch of other properties set
this.a = 0;
this.b = 1;
this.c = 2;
this.d = 3;
}
}
class CompanyRectangle extends Rectangle {
// Use an existing rectangle (r) as a base for the extended rectangle
constructor(r) {
super(r.height, r.width);
// copy over all the other properties that have been set
this.a = r.a;
this.b = r.b;
this.c = r.c;
this.d = r.d;
this.name = 'CompanyRectangle';
}
}
const r = new Rectangle(4, 2);
r.update(); // set the other properties
// create a new CompanyRectangle object, copying all the properties from 'r'
const cr = new CompanyRectangle(r);
最佳答案
您可以在 CompanyRectangle
构造函数中调用 Rectangle 类
的 update 方法,将所有属性从父类(super class)复制到子类;
class Rectangle {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
update() {
// Has a bunch of other properties set
this.a = 0;
this.b = 1;
this.c = 2;
this.d = 3;
}
}
class CompanyRectangle extends Rectangle {
// Use an existing rectangle (r) as a base for the extended rectangle
constructor(r) {
super(r.height, r.width);
// update method from super class here
super.update(this);
this.name = 'CompanyRectangle';
}
}
const r = new Rectangle(4, 2);
r.update(); // set the other properties
// create a new CompanyRectangle object, copying all the properties from 'r'
const cr = new CompanyRectangle(r);
console.log(cr);
关于javascript - 我可以使用类的现有实例来创建扩展子类的新对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58728629/