如果我有一个类,并且该类的实例将另一个类实例化为其属性之一,那么该属性如何影响父级的属性?例如在下面的示例中,我希望 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
}
}
}
最佳答案
您可以在创建时将 Person
实例传递给 Gpa
实例:
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);
这是简单的答案;更好的方法是在 Person 类中有一个方法来更新其 Gpa 实例并附加到数组。
关于javascript - 如何使一个类能够影响它实例化的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49544991/