我想扩展以下类(class):
class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}
get name() {
return this._name;
}
get age() {
return this._age;
}
}
...通过添加 sport
及其 getter:
class Athlete extends Person {
constructor(name, age, sport) {
super();
this._name = name;
this._age = age;
this._sport = sport;
}
get sport() {
return this._sport;
}
}
虽然上述方法有效,但我想避免重复基父构造函数的参数。以下方法不起作用:
class Athlete extends Person {
constructor(sport) {
super();
this._sport = sport;
}
get sport() {
return this._sport;
}
}
let athlete = new Athlete('Peter', 29, 'cricket');
console.log(athlete.name, athlete.age, athlete.sport); // name and age are not inherited, is returned 'undefined'
那么,如何在不重写基类字段的情况下向子类添加字段呢?
最佳答案
您需要传递参数,但可以通过将它们传递给 super()
来避免分配所有参数:
class Athlete extends Person {
constructor(name, age, sport) {
super(name, age); // pass arguments to super()
this._sport = sport;
}
get sport() {
return this._sport;
}
}
let athlete = new Athlete('Peter', 29, 'cricket');
console.log(athlete.name, athlete.age, athlete.sport);
关于javascript - 类继承 - 添加参数而不重写父构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66421801/