Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass ES6 default parameters from a subclass to its superclass?

I've got this code:

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

But calling myBush = new Bush({}) results in an object with the name "General Plant" instead of "General Bush". Is there any way to set the default values in the subclass without having to manually call this.name = name in the constructor?

like image 500
Andrew Avatar asked Oct 17 '22 12:10

Andrew


1 Answers

Default initialisers don't mutate the arguments object (such happened only in ye olde sloppy mode).
You need to pass the actual values from the parameter variables:

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

Alternatively (but with different behaviour for undefined values and surplus properties) you might employ Object.assign:

class Bush extends Plant {
  constructor(opts) {
    super(Object.assign({name: 'General Bush', height: 2, depth: 2}, opts));
  }
}
like image 81
Bergi Avatar answered Oct 21 '22 09:10

Bergi