I have example class:
class Something{
constructor(x, y){
this.x = x;
this.y = y;
}
//...
}
And when I'll make inherited class like this:
class Dog extends Something{
constructor(name){
this.name = name;
}
//...
}
Will Dog's constructor look like this?
constructor(x, y, name){
this.x = x;
this.y = y;
this.name = name;
}
If not, is it possible to make it working like this ^?
Is constructor inherited in JS ECMAScript 6?
Not really, no. But if you don't provide a constructor at all, the JavaScript engine provides a default that acts a bit like an inherited constructor.1 (Not relevant to your example, you've provided a constructor in Dog.)
Will Dog's class look like this?
No. Because you've defined the constructor in Dog, the JavaScript engine doesn't do anything for you; it's up to you to define Dog's constructor and have it call Something's via super (and you can't use this until you call super).
Your Dog constructor would need to either accept x and y, or hardcode its own (or derive them from the argument it does get):
Accepting them:
class Dog extends Something{
constructor(name, x, y) {
super(x, y);
this.name = name;
}
//...
}
Hardcoding:
// Accepting them:
class Dog extends Something{
constructor(name) {
super(42, 57);
this.name = name;
}
//...
}
(Or of course, accept only x or y and hardcode/derive the other one.)
1 If you don't supply constructor at all, the JavaScript engine adds one for you.
For base classes, it looks like this:
constructor() {
}
For derived classes, it looks like this:
constructor(...args) {
super(...args);
}
That latter one is why I say it's a bit like having an inherited constructor, because unlike languages like Java or C# where the default constructor accepts no arguments and calls super with no arguments, JavaScript's default passes through all arguments it receives.
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