Java脚本中的继承

时间:2019-05-29 13:08:42

标签: javascript inheritance

我有一个这样的人:

 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类的所有属性,该怎么办?例如,我不想继承interest属性。我是否要像这样排除它?

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});
    }
}

我仍然是初学者,所以我不确定这是否是好的做法。祝你有美好的一天!

2 个答案:

答案 0 :(得分:4)

继承意味着它的含义……您继承了父母给您的东西。因此,不建议使用“避免属性”(而且我不确定您是否可以做到)。

两种解决方案:

  • 明智的架构(我建议):在您的特定情况下,我只将interests放在Teacher类中。如果其他类也具有interests,我将创建一个像PersonInterest这样的子类,Teacher将继承自该子类。
  • 明智的做法:在不需要的类中将interests设置为nullundefined

答案 1 :(得分:4)

  super(name, age, gender); // I haven't included the interests property here

通过不向函数调用添加参数,该参数将隐式地未定义。因此,上限等于:

 super(name, age, gender, undefined)

因此interests属性仍然存在,它只是undefined。如果您所有的代码都假设无法定义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?

现在,您可以通过以下方式完全忽略undefined属性,而不是将现有属性设置为指示其为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中,请采用第一种方法(具有可选属性))