如何使用call()实现继承。错误:类构造函数不能在没有'new'的情况下被调用。

5

您能给我解释一下如何在使用 class 时实现继承吗?

当我使用 function 来定义构造函数时,一切都正常(参见代码版本1)。但是,当我将 function 转换为 ES2015 的 class(版本2)时,会产生以下错误:

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

我需要向代码中添加什么内容,还是应该保留 function

1. 使用 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. 使用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);


第一个能够工作是因为你使用了new关键字调用了Customer()函数。这使得该函数的行为类似于构造函数。因此,当该函数运行时,它将this初始化为{},并在你执行Person.call...时将其传递给Person。在JavaScript中,类是基于这些构造函数的语法糖,除了不能在没有new关键字的情况下调用它们之外。因此,第二个无法工作。 - Abhishek Mehandiratta
它还链接了构造函数,因此您可以执行(new Customer(...)) instanceof Person,其结果为true - Caramiriel
1个回答

5

事实上,当使用class定义Person时,不允许执行Person.call()操作。ES2015提供了extendssuper关键字来实现这种原型链定义:

class Customer extends Person {
  constructor(firstName, lastName, phone, membership) {
    super(firstName, lastName);
    this.phone = phone;
    this.membership = membership;
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接