Spedwards
Spedwards

Reputation: 4492

Extending Prototype, Inheritance, and Super

Consider the following code

const A = class {
    constructor(...args) {
        A.prototype.constructor.apply(this, args);
    }
};

A.prototype.constructor = function(name) {
    this.name = name;
};

A.prototype.print = function() {
    console.log(this.name);
};


const B = class extends A {};

B.prototype.print = function() {
    super.print();
    console.log('In B!');
};

The line of super.print() in B.prototype.print throws a Syntax error of 'super' keyword unexpected here. Why?

Why can I not call the class' super like any other language? What is the correct way of doing this?

Upvotes: 0

Views: 37

Answers (1)

Rowland Shaw
Rowland Shaw

Reputation: 38130

In JavaScript, to call the base class' implementation, you call it explicitly by name, i.e.:

B.prototype.print = function() {
    A.prototype.print.call(this);
    console.log('In B!');
};

Upvotes: 1

Related Questions