簡體   English   中英

Angularjs 到 Angular 遷移:工廠原型

[英]Angularjs to Angular Migration: factory prototype

我正在從 angularjs 遷移到 angular。 我已經做了很多,但我仍然堅持工廠和原型。 Card 代表一張撲克牌。


        function Card() {
            this.remoteId = 0;
            this.version = 0;
            this.name = "";
            this.stars = 0;
        }

       Card.prototype = {
            getFromRemote: getFromRemote,
            initFromRemote: initFromRemote,
            updateFromCard: updateFromCard,
            createImage: createImage,
           };


      return (Card);
     }

現在我只是想知道如何遷移它,因為 angular 中沒有更多的工廠。 我正在考慮使卡 function 成為像 angular 教程https://angular.io/tutorial/toh-pt1中的卡接口。 你認為這是個好主意還是我錯過了什么? 任何幫助或想法將不勝感激!!!!

您可以使用抽象 class 和構造函數的組合:

abstract class以獲取原型的功能。

初始值設置邏輯可以在go里面constructor 游樂場鏈接

 abstract class AbsCard {

  abstract remoteId: number;
  abstract version: number;
  abstract name: string
  abstract stars: number;

  public initFromRemote(): void {
    this.remoteId = 0;
  }

  public print() {
    console.log(this);
  }

}

class Card extends AbsCard {

  public remoteId: number = 0;
  version: number = 0;
  name: string = '';
  stars: number = 0;
  
  public constructor() { 
    super();
    /* other creation logic can come here */
  }
}

let c = new Card();
c.print();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM