6

! 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.

Sergio Nikolaev
  • 679
  • 8
  • 16
  • 4
    It invokes `constructor()` on the parent class. At the simple level, there's really only so much to say. Is there something in particular you're curious about? – S McCrohan Mar 03 '17 at 15:06
  • 1
    @SMcCrohan, maybe try to explain not in a simpler form. It invokes constructor() on the parent class - that was already grasped. But how does it invokes it? How does these arguments get passed from subclass to superclass through super() . I understand these steps (maybe) but not the actual mechanics behind them. Why cant we just use `.__proto__` and `.call` or `.apply`? – Sergio Nikolaev Mar 03 '17 at 15:30
  • Can anyone explain what happens here https://stackoverflow.com/questions/54685556/why-doesnt-reassigning-a-super-method-result-in-that-reassigned-method-being-ca in context of super – Umair Abid Feb 14 '19 at 11:55

1 Answers1

15

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).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375