我有一个像这样的 Person 类:
class Person {
constructor(name, age, gender, interests) {
Object.assign(this, {name, age, gender, interests});
}
}
我可以像这样创建子类:
class Teacher extends Person {
constructor(name, age, gender, interests, subject, grade) {
super(name, age, gender, interests);
Object.assign(this, {subject, grade});
}
}
但是如果我想创建子类但又不想继承 Person 类的所有属性怎么办?例如,我不想继承利益属性(property)。我是否只是像这样排除它:
class Student extends Person {
constructor(name, age, gender, height, weight) {
super(name, age, gender); // I haven't included the interests property here
Object.assign(this, {height, weight});
}
}
我还是初学者,所以我不确定这是否是一个好的做法。祝你有美好的一天!
最佳答案
super(name, age, gender); // I haven't included the interests property here
如果不向函数调用添加参数,该参数将隐式未定义。因此上部等于:
super(name, age, gender, undefined)
因此,interests
属性仍然存在,只是未定义
。如果您的所有代码都假设无法定义interests
,那么这实际上是一个很好的解决方案。如果没有,例如如果你在没有明确检查的情况下使用它进行计算,你的计算可能会突然变成 NaN,这会给你带来一些麻烦:
if(person.age > 18) {
alert("adult");
} else alert("child"); // or maybe the person is not a child, and it's age property was just not set?
现在,您可以完全省略 interests
属性,而不是将该现有属性设置为指示其未定义的值,方法是:
1)将其移动到子类:
class Person {
constructor(name, age, gender) {
Object.assign(this, {name, age, gender });
}
}
class PersonWithInterests extends Person {
constructor(name, age, gender, interests) {
super(name, age, gender);
Object.assign(this, { interests });
}
}
2)创建一个 Mixin:
Mixin 是一个类,可以扩展多个类。如果不止一个人有兴趣,那么为其创建一个 mixin 可能会有所帮助:
const Interested = Super => class InterestMixin extends Super {
constructor(args) { // passing in an object here makes the Mixin more flexible, all superclasses have to deal with it though
super(args);
this.interests = args.interests;
}
};
class Animal { }
const PersonWithInterest = Interested(Person);
const AnimalWithInterest = Interested(Animal);
new PersonWithInterest({ name: "Jonas", interests: 10 })
new AnimalWithInterest({ type: "bear", interests: 20 })
(如果您最终为每个属性创建一个新的 Mixin,则此解决方案不再真正可行。如果您无法将多个属性分组到一个有用的 Mixin 中,请使用第一种方法(具有可选属性)) .
关于javascript - JavaScript 中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56361422/