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