Sergio Nikolaev
Sergio Nikolaev

Reputation: 789

ES6 What does super() actually do in constructor function?

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

Upvotes: 6

Views: 4168

Answers (1)

Bergi
Bergi

Reputation: 664356

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

Upvotes: 15

Related Questions