我有一个像这样的人:

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

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

最佳答案

  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中,请采用第一种方法(具有可选属性))。

关于javascript - 用Java继承,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56361422/

10-12 16:49
查看更多