【问题标题】:Avoid initializing every variable inside class's constructor避免在类的构造函数中初始化每个变量
【发布时间】:2021-11-10 15:16:38
【问题描述】:

我有许多模型(它们是 javascript 类)为我的数据库保存名称,还有它的类型。有没有一种方法可以创建一个新用户,而不必在构造函数中调用所有这些属性?

class User {
    name: string;
    email: string;
    password: string;

    constructor(values: User) {
        this.name = values.name;
        this.email = values.email;
        this.password = values.password;

        // I don't want to call this.name, this.email, ... Since this User model is relatively small, but I have models with hundreds of attributes
    }
}

【问题讨论】:

    标签: javascript typescript class constructor


    【解决方案1】:

    在 typescript 中,您可以在构造函数的参数列表中创建类字段,如下所示:

    class User {
        // nothing here :)
        constructor(private name: string, private email: string, private password: string) {
            // empty :)
        }
    }
    

    如果你指定一个访问修饰符,你会自动获得声明和赋值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-27
      • 2015-02-19
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多