打字稿:自动更新一个类属性会导致另一个更新

时间:2019-04-16 03:32:02

标签: typescript

我已经看过这个了,却找不到任何可以解释如何做的地方。

我有一堂课

export class CalendarLayout {
   private displayedColumns: number;
   private displayedHours: number;
   private calendarStartDatePosition: moment.Moment;
   private dayDifference: number;


   constructor(
            displayedColumns: number,
            displayedHours: number,
            calendarStartDatePosition: moment.Moment,
            dayDifference: number
           ) {
    this.displayedColumns = displayedColumns;
    this.displayedHours = displayedHours;
    this.calendarStartDatePosition = calendarStartDatePosition;
    this.dayDifference = dayDifference;
}

}

我实际上希望dayDifference是基于calendarStartDatePosition的计算值。

dayDifference = this.calendarStartDatePosition.diff(moment(), 'days');

我尝试使用getter和setter徒劳无功。此外,编译器抱怨说它没有收到dayDifference的值。

您如何拥有一个类的属性(在我的情况下为“ dayDifference”),该属性本身是从其他属性之一计算而来的?此外,如果我更新了calendarStartDatePosition属性,则dayDifference属性会自动更新。

1 个答案:

答案 0 :(得分:1)

我已经在您提供的代码中插入了注释:

export class CalendarLayout {
    private displayedColumns: number;
    private displayedHours: number;
    private calendarStartDatePosition: moment.Moment;
    // private dayDifference: number;

    // We can define a getter (private as before).
    // This will *automatically* calculate the relevant value
    // when asked (via `this.dayDifference`, no method call).
    private get dayDifference() {
        return this.calendarStartDatePosition.diff(moment(), 'days');
    }

    constructor(
        displayedColumns: number,
        displayedHours: number,
        calendarStartDatePosition: moment.Moment,
        // dayDifference: number // Calculated automatically
    ) {
        this.displayedColumns = displayedColumns;
        this.displayedHours = displayedHours;
        this.calendarStartDatePosition = calendarStartDatePosition;

        // We no longer need to set this, as we're calculating it as needed.
        // this.dayDifference = dayDifference;
    }
}

我不熟悉Moment.js,但您可能想要一个可以从中获取当前时间的全局对象;我相信当前代码会在每次调用时创建一个新实例。