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

标签 javascript node.js class

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

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

相关文章:

python - 如何在对象中添加数据并在其他对象中将信息插入数组中?

javascript - res.redirect 没有重定向到任何地方

javascript 按内部数据对数组进行排序

node.js 中的 Ajax 文件上传

mysql - 无法使用sequelize连接带有外键的2个表

C++:如何解决具有多个多态输入的方法调用?

powershell - Power Shell类方法调用它是自己的方法语法错误

javascript - 为删除按钮提供功能

javascript - 通过 Zapier 代码发布到 Webhooks

javascript - 语法错误: Unexpected token v in JSON at position 2