#author("2023-05-07T14:42:36+09:00","default:ryuichi","ryuichi")
#author("2023-05-07T17:02:50+09:00","default:ryuichi","ryuichi")
* オブジェクトを拡張する時のオブジェクトリテラルとクラスの比較 [#aa530659]
** A:オブジェクトリテラル、B:クラス [#ka71929a]
** オブジェクトの作成 [#ka71929a]
*** A:オブジェクトリテラル [#cb4c8e1b]
type TA = {
name: string;
getLength: () => number;
};
const A = (val: string): TA => {
const name = val;
const getLength = () => {
return name.length;
};
return {
name,
getLength,
};
};
*** B:クラス [#fe950644]
class B {
name: string = "";
constructor(val: string) {
this.name = val;
}
getLength() {
return this.name.length;
}
}
*** AとBの使用 [#re0bb012]
const _a = A("AAA");
console.log(_a.getLength());
const _b = new B("BBB");
console.log(_b.getLength());
ほぼ同じ機能
** オブジェクトの拡張 [#i7a714cc]
*** Aの拡張 [#ccfae9a0]
const _a2: TA & { x: number } = { ..._a, x: 1 };
console.log(_a2.getLength(), _a2.x);
*** Bの拡張 [#s39718fe]
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はクラスなので記述が冗長になる