如何使类能够影响它实例化的类?

时间:2018-03-28 22:10:35

标签: javascript class

如果我有一个类,并且该类的实例将另一个类实例化为其属性之一,那么该属性如何影响父属性?例如在下面的示例中,我希望Gpa类能够修改它所属的Person。

class Person {
  constructor (name, gpa) {
    this.name = name;
    this.happynessHistory = [];
    this.gpa = new Gpa(gpa);
  }
}
class Gpa {
  constructor (startingGpa) {
    this.score = startingGpa;
  }
  updateGpa (newGpa) {
    this.score = newGpa:
    if (this.score < 3.0) {
      // push 'true' to the Person's happynessHistory array
    } else {
      // push 'false' to the Person's happynessHistory array
    }
  }
}

2 个答案:

答案 0 :(得分:1)

您可以在创建Person实例时将其传递给Gpa实例:

&#13;
&#13;
class Person {
  constructor (name, gpa) {
    this.name = name;
    this.happynessHistory = [];
    this.gpa = new Gpa(gpa, this); // pass parent
  }
}
class Gpa {
  constructor (startingGpa, person) {
    this.score = startingGpa;
    this.person = person;
  }
  updateGpa (newGpa) {
    this.score = newGpa;
    this.person.happynessHistory.push(this.score < 3.0);
  }
}

var p = new Person("Test", 4.0);
p.gpa.updateGpa(2.0);
console.log(p.happynessHistory);
&#13;
&#13;
&#13;

这是直截了当的答案;更好的方法是在Person类中有一个方法来更新其Gpa实例并附加到数组。

答案 1 :(得分:0)

您希望影响person,但您没有Person的实例。

在委托模式中,您尝试做的事情会更有意义。

例如,

&#13;
&#13;
const Person = {
  init(name, gpa) {
    this.name = name;
    this.gpa = Object.create(Gpa);
    this.gpa.init(gpa, this);
    this.happinessHistory = [];
  },
};

const Gpa = {
  init(startingGpa, person) {
    this.score = startingGpa;
    this.person = person;
  },
  updateGpa(newGpa) {
    this.score = newGpa;
    if (this.score < 3.0) {
      this.person.happinessHistory.push(true);
    } else {
      this.person.happinessHistory.push(false);
    }
  },
};

var john = Object.create(Person);
john.init('John', 3.3);
var amy = Object.create(Person);
amy.init('Amy', 2.2);
amy.gpa.updateGpa(1.0);
console.log(amy.happinessHistory);
&#13;
&#13;
&#13;