如何将ES6默认参数从子类传递到其超类?

时间:2017-05-08 20:33:32

标签: javascript ecmascript-6

我有这段代码:

class Plant {
  constructor({name = 'General Plant', height = 0, depth = 1, age = 0}) {
    this.name = name;
    this.stats = {
      height: height,
      depth: depth,
      age: age
    };
  }
}

class Bush extends Plant {
  constructor({name = 'General Bush', height = 2, depth = 2}) {
    super(arguments)
  }
}

但是调用myBush = new Bush({})会产生一个名为“General Plant”而不是“General Bush”的对象。有没有办法在子类中设置默认值而无需在构造函数中手动调用this.name = name

1 个答案:

答案 0 :(得分:2)

默认初始化程序不会改变arguments object(这种情况只发生在草率模式中)。
您需要传递参数变量的实际值:

class Bush extends Plant {
  constructor({name = 'General Bush', height = 2, depth = 2, age}) {
    super({name, height, depth, age});
  }
}

或者(但undefined值和剩余属性的行为不同),您可以使用Object.assign

class Bush extends Plant {
  constructor(opts) {
    super(Object.assign({name: 'General Bush', height: 2, depth: 2}, opts));
  }
}