您能给我解释一下如何在使用 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);
this
初始化为{},并在你执行Person.call...
时将其传递给Person。在JavaScript中,类是基于这些构造函数的语法糖,除了不能在没有new关键字的情况下调用它们之外。因此,第二个无法工作。 - Abhishek Mehandiratta(new Customer(...)) instanceof Person
,其结果为true
。 - Caramiriel