是否可以使用类的现有实例来创建扩展子类的新对象?
在下面的示例中,我有一个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);