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

霸气de小男生 提交于 2021-02-07 14:20:08

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/54064489/how-to-use-call-for-inheritance-error-class-constructor-cannot-be-invoked-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!