Why do I need to reference the base class' constructor in the subclass? I seem to get the same result either way.
class Animal {
constructor(age) {
this.age = age;
}
}
class Mammal extends Animal {}
let lion = new Mammal(3);
lion.age //=> 3
as opposed to
class Mammal extends Animal {
constructor(){
super(3)
}
}
let lion = new Mammal();
lion.age //=> 3
If you don't provide an explicit constructor, in a subclass1 the JavaScript engine will generate one for you that looks like this:
constructor(...args) {
super(...args);
}
That's what's going on in your first example. So this:
class Mammal extends Animal {
}
is the same as this:
class Mammal extends Animal {
constructor(...args) {
super(...args);
}
}
...it's just that the second is explicit, whereas the first is using the constructor inserted into the class for you by the JavaScript engine.
This is defined in Step 10 of §14.5.14: Runtime Semantics: ClassDefinitionEvaluation:
If constructor is empty, then
If ClassHeritageopt is present, then
Let constructor be the result of parsing the source text
constructor(... args){ super (...args);}
using the syntactic grammar with the goal symbol MethodDefinition.
Else,
Let constructor be the result of parsing the source text
constructor( ){ }
using the syntactic grammar with the goal symbol MethodDefinition.
1 If it's not a subclass, as you can see above, it's just constructor() { }
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments