如何继承class并调用父构造函数?
How to inherit class and call a parent constructor?
我创建了一个 class:
class Human {
constructor(name){
this.name = name;
}
greet(){
alert(this.name);
}
}
它工作正常。但是,当我尝试从 class 继承时,出现错误
class Person extends Human{
constructor(name, age){
super.constructor(name);
this.age = age;
}
greet(){
super.greet(this.name + this.age);
}
}
var no = new Person("Brent", 65);
我有这样的错误 - this
在 Person class constructor.
中使用未初始化
我怎样才能正确继承,以便它同时提醒年龄和姓名?
您只需在构造函数中调用 super()
。
要调用父构造函数,您需要对实例使用super(…)
not super.constructor(…)
. This special super
call will initialise the this
keyword in the extend
ing class。
我创建了一个 class:
class Human {
constructor(name){
this.name = name;
}
greet(){
alert(this.name);
}
}
它工作正常。但是,当我尝试从 class 继承时,出现错误
class Person extends Human{
constructor(name, age){
super.constructor(name);
this.age = age;
}
greet(){
super.greet(this.name + this.age);
}
}
var no = new Person("Brent", 65);
我有这样的错误 - this
在 Person class constructor.
我怎样才能正确继承,以便它同时提醒年龄和姓名?
您只需在构造函数中调用 super()
。
要调用父构造函数,您需要对实例使用super(…)
not super.constructor(…)
. This special super
call will initialise the this
keyword in the extend
ing class。