为 getter 提供默认值,而不会在 Angular 2 模型类中导致堆栈溢出

Provide default value to getter without causing stack overflow in Angular 2 Model Class

本文关键字:模型 栈溢出 堆栈 Angular getter 默认值      更新时间:2023-09-26

所以我试图找到一种方法来为 JavaScript 中的类的 getter 提供回退行为。这个想法是,如果正在访问的属性在创建时设置为 null,则提供另一个属性(标题)的修改版本。我面临的问题是获取字幕属性时递归调用,因为它正在访问自身。我会简单地重命名为 _subtitle,但使用 TypeScript,您必须修改界面并提供一个一次性的临时值 _subtitle 除了字幕之外,这会破坏界面的语义。

export interface IFoo {
  title: string;
  subtitle?: string;
}
export class Foo implements IFoo {
  public title: string;
  public set subtitle(val) {
     this.subtitle = val;
  }
  public get subtitle() {
    return this.subtitle ? this.subtitle : this.title.split('//')[0];
  };
  constructor(obj?: any) {
    this.title = obj && obj.title || null;
}
因此,

我实际上不久后就意识到,您始终可以使用私有属性之类的东西作为"临时"存储位置,而不会破坏接口的语义或契约。因此,通过一些简单的更改,我的二传手/吸盘手就可以工作了!

  //...
  // 
  private _subtitle: string;
  public set subtitle(val) {
    this._subtitle = val;
  }
  public get subtitle() {
    return this._subtitle ? this._subtitle : this.title.split('//')[1].trim();
  };
  //...