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
?
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);
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);
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With