[英]Class constructor parameters in TypeScript
我正在瀏覽有關 TypeScript 的一些編碼風格。
當從一個類初始化一個對象時。 TypeScript 中這兩種代碼風格的優缺點是什么?
class Class3 {
// members
private readonly m1: Class1;
private readonly m2: Class2;
constructor({
_m1 = new Class1(),
_m2 = new Class2()
}:{_m1:Class1, _m2:Class2}){
this.m1 = _m1;
this.m2 = _m2;
}
public foo() {
console.log("Hello World a");
}
}
class Class3 {
// members
private readonly m1: Class1;
private readonly m2: Class2;
constructor() {
this.m1 = new Class1();
this.m2 = new Class2();
}
public foo() {
console.log("Hello World b");
}
}
class Robot {
private readonly brain: Brain
private readonly laserBeam: LaserBeam
constructor({
// destructuring and providing default values
brain = new Brain(),
laserBeam = new LaserBeam()
}: {
// type signature for constructor options
brain: Brain
laserBeam: LaserBeam
}) {
// attaching these members to this instance
this.brain = brain
this.laserBeam = laserBeam
}
async destroyHumanity() {
await this.brain.think()
await this.laserBeam.charge()
await this.laserBeam.fire()
console.log("Goodbye world!")
}
}
這是一個強大的模式,可以用於很多事情。
不幸的是它是多么冗長,有太多重復,但除此之外它是一個很好的模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.