ES6 - Super Required In Constructor
Solution 1:
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.
Solution 2:
Axel FTW http://www.2ality.com/2015/02/es6-classes-final.html
Summary
Why super is required?
- The new keyword
class
isn't just syntax sugar. - Allocation and instantiation only happens in the base constructor.
But why this?
- To allow exotic objects to be extended (thank you Felix Kling).
Post a Comment for "ES6 - Super Required In Constructor"