5

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);
trincot
  • 317,000
  • 35
  • 244
  • 286
  • The first one worked because you called Customer() with new keyword. That makes the function behave like a constructor function. So when the function ran, it initialized `this` to {}, which was passed to Person when you did `Person.call...`, classes in js are syntactical sugar on top of these constructor functions, except for the fact that they cannot be called without new keyword. Hence second one doesnt work – Abhishek Mehandiratta Jan 06 '19 at 18:16
  • It also links up the constructor, so you can do `(new Customer(...)) instanceof Person`, which is `true`. – Caramiriel Jan 06 '19 at 18:45

1 Answers1

5

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;
  }
}
trincot
  • 317,000
  • 35
  • 244
  • 286