Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 458
Serge Nikolaev Avatar asked Mar 03 '17 15:03

Serge Nikolaev


People also ask

Is Super necessary in constructor?

Output. If the SuperClass has a default Constructor there is no need to call it using"super()" explicitly, it will be invoked implicitly.

What does super () do in JS?

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 es6?

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.

What does the Super keyword do when invoked from within a constructor?

Use of super with constructors The super keyword can also be used to access the parent class constructor.


1 Answers

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

like image 131
Bergi Avatar answered Oct 28 '22 09:10

Bergi