Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将ES6默认参数从子类传递到其超类?_Javascript_Ecmascript 6 - Fatal编程技术网

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

Javascript 如何将ES6默认参数从子类传递到其超类?,javascript,ecmascript-6,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({

我有这个密码:

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

默认初始值设定项不会改变(只有在旧的邋遢模式下才会发生这种情况)。
您需要传递参数变量的实际值:

class Bush extends Plant {
  constructor({name = 'General Bush', height = 2, depth = 2, age}) {
    super({name, height, depth, age});
  }
}
或者(但对于
未定义的
值和剩余属性的行为不同),您可以采用:


我知道当我调用
super(arguments)
时,它是提供给
newbush
的原始参数。我想知道是否有一种方法可以传递已经修改过的参数。因此,如果我懒得多次写入变量名(我就是这样),那么我就必须放弃使用新的ES6默认参数,并手动扩展参数,如:
constructor(){super($.extend(arguments),{name:'General Bush',…}
?引入变量只是为了多次使用它们:-)注意
$.extend
(或者更好的
Object.assign
)与默认初始化器的语义稍有不同。是的,我刚刚意识到我应该在我的示例中使用
Object.assign
。仍然使用老式的jQuery来填补ES5的漏洞。我想我必须放弃使用构造函数的默认参数,因为我的设置方式在调用
时仍然会出错>没有对象的新Bush()
。@Andrew显然不需要。这非常有效:
constructor(){super(object.assign({name:'General Bush',height:2,depth:2},…arguments))}
class Bush extends Plant {
  constructor(opts) {
    super(Object.assign({name: 'General Bush', height: 2, depth: 2}, opts));
  }
}