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

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

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

您可以在Rectangle class构造函数中从CompanyRectangle调用update方法,以将所有属性从超类复制到子类;

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);

,

class Rectangle {
    constructor(height,width,otherProperties) {
      this.name = 'Rectangle';
      this.height = height;
      this.width = width;
        if (otherProperties) {
            this.a = otherProperties.a;
            this.b = otherProperties.b;
            this.c = otherProperties.c;
            this.d = otherProperties.d;
        }
    }
    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,r);
  
      // copy over all the other properties that have been set
      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)

本文链接:https://www.f2er.com/3152843.html

大家都在问