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