网站搜索

html - 在 Angular 中,我如何将一个类的变量设置为函数的结果?


我希望能够实时获取另一个类的数组总和的更新。

Detachment 类有一个属性 CP,我希望 Army 类能够获取其所有 Detachment 的 CP 总和,并使其对任何创建自己 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 相当陌生,所以我不确定如何模拟这种行为。

答案#1

你可以用这样的 getter 来解决这个问题:

get CP(): number { return this.getArmyCP(); }

所以从外部来看,你可以像使用普通变量一样使用它,它实际上会调用 getter:

let myArmyCP = army.CP;