0

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

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

2 回答 2

1

Rectangle class您可以在构造函数中调用 update 方法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);
    // 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);

于 2019-11-06T11:13:25.743 回答
0

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)

于 2019-11-06T11:20:58.253 回答