【问题标题】:How to init/set value in a superclass constructor? in Typescript如何在超类构造函数中初始化/设置值?在打字稿中
【发布时间】:2018-12-17 22:04:24
【问题描述】:

鉴于这两个类:

用户

    export class User {

        constructor(id?: string, userName?: string, fullName?: string,
 email?: string, jobTitle?: string, phoneNumber?: string, roles?: string[]) {
            this.id = id;
            this.userName = userName;
            this.fullName = fullName;
            this.email = email;
            this.jobTitle = jobTitle;
            this.phoneNumber = phoneNumber;
            this.roles = roles;
        }

    }

UserEditUser

扩展
import { User } from './user.model';


export class UserEdit extends User {
    constructor(currentPassword?: string, newPassword?: string, confirmPassword?: string) {
        super();

        this.currentPassword = currentPassword;
        this.newPassword = newPassword;
        this.confirmPassword = confirmPassword;
    }

    public currentPassword: string;
    public newPassword: string;
    public confirmPassword: string;

}

可能从 UserEditemail 设置为空字符串'',从创建新对象开始?。例如。

let userEdit:UserEdit = new UserEdit()

【问题讨论】:

  • 为什么使用类而不是接口?

标签: javascript typescript oop object


【解决方案1】:

您需要在基类中使用super(param1, param2, param3, ...) 传递参数

你的情况

super(id, userName, fullName, email, jobTitle, phoneNumber, roles);

super(id, username, fullname, '', jobTitle, phoneNumber, roles);

【讨论】:

  • 我想要的是创建一个对象new UserEdit() 并从中将电子邮件设置为空字符串''。
  • 好的,使用 super 设置或取消设置它们。我的回答与您的需要有关。检查super的用法。 super 初始化基本构造函数。所以你需要像上面那样调用它
  • 另外,您的User 类没有任何作为类而不是接口的好处。如果它是一个接口,您可以让 UserEdit 实现它(或 Partial<User> 用于可选字段),然后正常与字段交互。
  • 是的,但我继承了这个项目。正如披头士乐队所说,如果有效,那就顺其自然吧。
  • 如果你不知道自己在做什么,你只能为别人唱歌。问候
【解决方案2】:

感谢 Simonare,我还找到了另一个优雅的解决方案,函数组合

像这样。

public user: User = new User('', '', '', '', '', '', ['']);
public userEdit: editUser = new UserEdit('', '', '');
public edit = () => { ...this.user, ...this.userEdit };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2017-01-12
    • 2016-01-05
    • 2010-11-28
    相关资源
    最近更新 更多