オブジェクトを拡張する時のオブジェクトリテラルとクラスの比較

オブジェクトの作成

A:オブジェクトリテラル

 type TA = {
   name: string;
   getLength: () => number;
 };
 
 const A = (val: string): TA => {
   const name = val;
   const getLength = () => {
     return name.length;
   };
   return {
     name,
     getLength,
   };
 };
 

B:クラス

 class B {
   name: string = "";
   constructor(val: string) {
     this.name = val;
   }
   getLength() {
     return this.name.length;
   }
 }

AとBの使用

 const _a = A("AAA");
 console.log(_a.getLength());
 const _b = new B("BBB");
 console.log(_b.getLength());

ほぼ同じ機能

オブジェクトの拡張

Aの拡張

 const _a2: TA & { x: number } = { ..._a, x: 1 };
 console.log(_a2.getLength(), _a2.x);

Bの拡張

 class BExtended extends B {
   x: number;
 
   constructor(val: string, x: number) {
     super(val);
     this.x = x;
   }
 }
 
 const _b2 = new BExtended("CCC", 1);
 console.log(_b2.getLength(), _b2.x);

Bはクラスなので記述が冗長になる


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS

Last-modified: 2023-05-07 (日) 17:02:50