gpt4 book ai didi

javascript - 我可以使用类的现有实例来创建扩展子类的新对象吗?

转载 作者:行者123 更新时间:2023-12-02 22:36:17 24 4
gpt4 key购买 nike

是否可以使用类的现有实例来创建扩展子类的新对象?

在下面的示例中,我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com