javascript - 在打字稿中传递参数的另一种方法
问题描述
我有一个打字稿类和一个方法。此方法采用三个参数。
class MyClass {
public static carStatus(name : string , color : string , isReady : boolean){
let result = isReady ? 'is ready' : 'is not ready';
return `${color} ${name} ${result}.`;
}
}
let carStatus = MyClass.carStatus('pride' , 'white' , true);
console.log(carStatus);
我想将(isReady)
括号中的第三个参数设置为方法。我知道可以通过这种方式完成:
class MyClass {
public static isReady : boolean;
public static carStatus(name : string , color : string){
let result = this.isReady ? 'is ready' : 'is not ready';
return `${color} ${name} ${result}.`;
}
}
MyClass.isReady = false;
let carStatus = MyClass.carStatus('pride' , 'white');
console.log(carStatus);
还有另一种方法可以做到这一点吗?
解决方案
我相信最简单的方法是使用单独的方法来设置isReady
值和没有静态方法的单个CarStatus
类:
class CarStatus {
private isReady: boolean;
constructor(private name: string, private color: string) {
this.name = name;
this.color = color;
}
public setReady() {
this.isReady = true;
}
public getStatus(): string {
let result = this.isReady ? 'is ready' : 'is not ready';
return `${this.color} ${name} ${result}.`;
}
}
let carStatus = new CarStatus("pride", "white");
carStatus.setReady();
console.log(carStatus.getStatus());
如果您认为每个概念都不是必需的或可以在不同时间设置,您也可以使用流利的方法。视情况而定,这可能是一种矫枉过正,举个例子:
class CarStatus {
constructor(private name: string, private color: string, private isReady: boolean) {
this.name = name;
this.color = color;
this.isReady = isReady;
}
public getStatus(): string {
let result = this.isReady ? 'is ready' : 'is not ready';
return `${this.color} ${name} ${result}.`;
}
}
class CarStatusBuilder {
private name: string;
private color: string;
private isReady: boolean;
public SetReady(): CarStatusBuilder {
return new CarStatusBuilder() { this.isReady = true};
}
public WithName(name: string): CarStatusBuilder {
this.name = name;
return this;
}
public WithColor(color: string): CarStatusBuilder {
this.color = color;
return this;
}
public Build(): CarStatus{
return new CarStatus(this.name, this.color, this.isReady);
}
}
let carStatus = new CarStatusBuilder()
.WithColor("white")
.WithName("pride")
.Build();
console.log(carStatus.getStatus());
推荐阅读
- opengl - glMultiDrawElementsIndirect 自定义 drawID,每个 DrawElementsIndirectCommand 有多个实例
- c++ - 使用 FFmpeg 库处理 GIF - 在 av_parser_init 中找不到解析器
- swift - 快速创建动态添加按钮
- r - R 中的 Maxent 错误:偏置网格不能与 SWD 格式背景一起使用
- python - 如何使用 discord.py 审查坏词
- qt - QT3D Multiview - 小部件中的单一视图
- c++ - 不同公式的不同回报但相同的值
- python - 使用自定义 pdf 求解具有随机变量的 ODE
- javascript - 带有鼠标和自定义右键的选择器
- python - 2 人骰子游戏,其中偶数总得分和奇数总失分 NEA 任务计算机科学