And*_*rew 5 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在构造函数中手动调用?
默认初始化程序不会改变arguments对象(这种情况只发生在旧的草率模式下)。
您需要传递参数变量的实际值:
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));
  }
}
| 归档时间: | 
 | 
| 查看次数: | 426 次 | 
| 最近记录: |