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?
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With