Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use call() for inheritance. Error: Class constructor cannot be invoked without 'new'

Can you explain me how to implement inheritance when using class?

When I use function for defining the constructor, everything works (cf. code version 1). But when I turn function into an ES2015 class (version 2) it produces this error:

Uncaught TypeError: Class constructor Person cannot be invoked without 'new'

Do I need to add something to the code or should I just leave it as it is with function?

1. Working code using function

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

function Customer(firstName, lastName, phone, membership) {
  Person.call(this, firstName, lastName);
  this.phone = phone;
  this.membership = membership;
}

const customer1 = new Customer("Tom", "Smith", "555-555-555", "Standard");
console.log(customer1);

2. Failing code using class

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

class Customer {
  constructor(firstName, lastName, phone, membership) {
    Person.call(this, firstName, lastName); // <--- TypeError
    this.phone = phone;
    this.membership = membership;
  }
}

const cust1 = new Customer("Bob", "Johnes", "555-222-333", "Silver");
console.log(cust1);
like image 791
Maciek Celiński Avatar asked Jan 06 '19 18:01

Maciek Celiński


1 Answers

Indeed, it is not allowed to do Person.call() when Person is defined with class. ES2015 offers the extends and super keywords for achieving such prototype-chain definition:

class Customer extends Person {
  constructor(firstName, lastName, phone, membership) {
    super(firstName, lastName);
    this.phone = phone;
    this.membership = membership;
  }
}
like image 142
trincot Avatar answered Sep 30 '22 12:09

trincot