我希望能够实时更新另一个类的数组的总数。
Detachment 类有一个属性 CP
,我希望 Army 类能够从其所有 Detachment 中获取其总和,并使创建自己的 Army 的任何对象都可以访问该属性。
export class Army {
cost: number;
CP: number;
name: string;
Detachments: Detachment[];
constructor() {
this.cost = 0;
this.name = "";
this.Detachments = [];
this.CP = this.getArmyCP();
}
getArmyCP() {
let total = 0;
for(let i=0; i<this.Detachments.length; i++) {
total += this.Detachments[i].CP;
}
return total;
}
}
我可以通过直接访问Army.getArmyCP()
来查看该值,但是是否可以设置Army.CP通过引用来访问该函数?
我已经能够在 AngularJS 中做到这一点,但我对 Angular 和 TypeScript 相当陌生,所以我不确定如何模拟这种行为。
最佳答案
你可以用 getter 来解决这个问题像这样:
get CP(): number { return this.getArmyCP(); }
所以从外部你可以像普通变量一样使用它,它实际上会调用 getter:
let myArmyCP = army.CP;
关于html - 在 Angular 中,如何将类的变量设置为函数的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46469913/