如何使用call()进行继承.错误:如果没有"new",则无法调用类构造函数 [英] How to use call() for inheritance. Error: Class constructor cannot be invoked without 'new'
问题描述
您能解释一下使用 class
时如何实现继承吗?
Can you explain me how to implement inheritance when using class
?
当我使用 function
定义构造函数时,一切正常(参见代码版本1).但是,当我将 function
转换为ES2015 class
(版本2)时,会产生以下错误:
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:
未捕获的TypeError:类构造函数无法在没有'new'的情况下调用Person
Uncaught TypeError: Class constructor Person cannot be invoked without 'new'
我是否需要在代码中添加一些内容,还是应该使用 function
使其保持原样?
Do I need to add something to the code or should I just leave it as it is with 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 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);
推荐答案
实际上,当 Person
用<代码>类.ES2015提供了 extends
和 super
关键字来实现原型链定义:
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;
}
}
这篇关于如何使用call()进行继承.错误:如果没有"new",则无法调用类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!