javascript - 如何使一个类能够影响它实例化的类?

标签 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
    }
  }
}

最佳答案

您可以在创建时将 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/

相关文章:

javascript - 如何在没有父节点为空的情况下删除javascript中的节点

java - 以编程方式打印类直方图

c++ - 编译器向空类声明添加了什么?

c++ - 指向同一类(C++)中的成员函数的指针?

javascript - 如何使用不同的 div ID 调用相同的函数?

javascript - 如何防止用户手动访问网址,要求他们单击链接才能到达那里

javascript - 如何防止 google oauth 自动登录?

javascript - 遍历JavaScript中的数组

Python-如何查找变量是否是特定类?

python - 类型错误 : endturn() missing 1 required positional argument: 'self'