假设我有一个程序:
class Program {
constructor() {
this.profileManager = new ProfileManager();
}
saveProgramConfig() {
// ...
}
}
如果ProfileManager
内部发生了一些事情,并且需要保存程序配置,那么从ProfileManager
类内部访问该特定实例的saveProgramConfig
方法的最佳方式是什么?
您可以将实例作为参数传递,以便两个实例都有彼此的链接:
this.profileManager = new ProfileManager(this);
并让ProfileManager将实例保存到自己的某个属性中,并在需要时对其调用saveProgramConfig
。
以下方法有什么问题?您可以在ProfileManager类中访问Program的测试方法。
class Program {
test() {
return "Hello World";
}
}
class ProfileManager extends Program {
constructor() {
super();
}
main() {
return this.test();
}
}
const tp = new B;
console.log(tp.main());