What is the "super()" operator for in Javascript?

Asked

Viewed 409 times

2

What is the operator’s functionality super() which lies within the method constructor?

1 answer

2


It is not an operator, it is a way of calling a constructor in a specific way, so it is a construction of the language through a keyword.

It serves precisely to call the builder of the inherited class there. " Whenever" makes a constructor in a derived class you must want to make a specific construction of it, but for the object to be complete you must make the construction part of the base class (the mother). So that’s the way to do it.

In fact this word is used to access the whole base object, so you can use to call its method and properties, the constructor is only one of them.

Knows the this, right? Which is what you use to access the current object. It is the this of the base object and not the current one.

In the constructor it should be used before any this, so you should start building the base object first and then move the current object you’re building.

To be clearer is not that there will be two objects, there will be only one, but it will be an object that has two logical parts, one that has been defined in the base class and the other that is defined in the current class. There are no physically two things apart, just to better understand the issue of inheritance.

This gives error because it is not building the part of the base object:

class Rectangle {
    constructor(height, width) {
        this.name = 'Rectangle';
        this.height = height;
        this.width = width;
    }
    sayName() {
        console.log('Hi, I am a ', this.name + '.');
    }
    get area() {
        return this.height * this.width;
    }
    set area(value) {
        this._area = value;
    }
}

class Square extends Rectangle {
    constructor(length) {
//        super(length, length);
        this.height;
        this.name = 'Square';
    }
}

console.log(new Square(10));

I put in the Github for future reference.

That one super() it’s like I’m calling new Rectangule(length, length);, But why don’t you call it that? Precisely because you do not want to create another object, the object is being created right there, but you want part of it that was inherited to be initialized there in the current constructor. Why don’t you call it yourself? Because you can have other builders and the way you call it might not be that simple. You can only do that if you’re a standard builder.

Understand What good is a builder?.

There are a number of rules to follow as can be seen in documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.