! Hola, amigos. I have this little class inheritance structure
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y);
this.color = color;
}
toString() {
return super.toString() + ' in ' + this.color;
}
}
let newObj = new ColorPoint(25, 8, 'green');
It compiles to this jsfiddle
I get how it works in es6 in a silly way. But could somebody explain how does it work under the hood in es5. In a simpler form.
Output. If the SuperClass has a default Constructor there is no need to call it using"super()" explicitly, it will be invoked implicitly.
The super keyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor. The super. prop and super[expr] expressions are valid in any method definition in both classes and object literals.
Why is super used? Is used for creating and initializing an object. It's a simple function. Is used as an "object" which calls the parent class.
Use of super with constructors The super keyword can also be used to access the parent class constructor.
super(…);
is basically sugar for this = new ParentConstructor(…);
. Where ParentConstructor
is the extended class, and this =
is the initialisation of the this
keyword (well, given that that's forbidden syntax, there's a bit more than sugar to it). And actually it will inherit from the proper new.target.prototype
instead of ParentConstructor.prototype
like it would from new
. So no, how it works under the hood does not compare to ES5 at all, this is really a new feature in ES6 classes (and finally enables us to properly subclass builtins).
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