我有一个打字稿类和一个方法。 此方法需要三个参数。
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);
还有另一种方法吗?
答案 0 :(得分:0)
我认为最简单的方法是使用一个单独的方法来设置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());