Why isn't super()
auto called in constructor?
So you can decide where in the constructor to call it. This is perfectly valid, for instance:
constructor(foo) {
let bar;
if (foo) {
bar = /*...*/;
} else {
bar = /*...*/;
}
super(bar);
}
...provided no code prior to the call to super
uses this
(or super.xyz
).
Yes, it would have been possible to define the language such that if you didn't have any call to super
in your constructor at all, it was added automatically for you at the beginning (a'la Java), but they just decided not to do it that way.
Is super()
here calling the base constructor AND setting the prototype? Seems wrong.
No, it's calling the base constructor. The prototype was set before your constructor was called. It's exactly like this old ES5 code:
function Derived() {
Base.call(this);
}
...in:
function Base() {
}
function Derived() {
Base.call(this);
}
Derived.prototype = Object.create(Base.prototype);
Derived.prototype.constructor = Derived;
Why is super()
required? Even when I've no intention of calling the base constructor.
If you have no intention of calling the base constructor, then your subclass isn't a subclass and shouldn't be extending the base. In a strictly-typed language you'd probably make the base (or a subset of the base) an interface and have your class implement that rather than subclassing. In JavaScript, no need, just make it quack like the duck you want it to be. If an instanceof
relationship is important, create a new base that will act like an interface but doesn't do anything anywhere, and have the old base and your class subclass it directly.
super()
auto called in constructor?" Which arguments should be passed to it? None, all or a subset? Any decision would probably lead to a discussion why that approach was chosen and not another...super()
is required always. Try to write a valid ES6 constructor withoutsuper()
.super()
required? Even when I've no intention of calling the base constructor." Becausethis
needs to be initialized properly (i.e. the object generated by calling the constructor needs to be constructed properly). That is primarily a concern for extending exotic objects / classes, such asArray
.