【问题标题】:Another way to pass arguments in typescript在打字稿中传递参数的另一种方法
【发布时间】:2020-03-05 06:47:03
【问题描述】:

我有一个打字稿类和一个方法。 此方法接受三个参数。

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);

还有其他方法吗?

【问题讨论】:

  • “更好”始终取决于用例,即您要解决的问题。将代码减少到一行几乎从来都不是“更好”的方式。但在你的情况下:你不应该在这里使用静态方法和字段。在这里,您可以放弃课程而只使用脚本。您的课程没有任何价值。
  • @Andreas_D 感谢您的建议。是的,你说得很对。当然,我在问题中写的代码只是一个简单的例子,我从不使用静态方法和类来做到这一点。因此,根据您的评论,我已经编辑了问题文本。

标签: javascript typescript typescript-class


【解决方案1】:

我相信最简单的方法是使用单独的方法来设置 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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 2021-09-27
    • 2014-02-24
    • 2021-03-25
    • 2016-05-17
    • 2015-08-14
    相关资源
    最近更新 更多