繁体   English   中英

如何在超类构造函数中初始化/设置值? 在打字稿中

[英]How to init/set value in a superclass constructor? in Typescript

给定这两个类:

用户

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

    }

和从User 扩展的 UserEdit

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;

}

创建新对象后,可以从UserEdit中将email设置为空字符串”。 例如。

let userEdit:UserEdit = new UserEdit()

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

在你的情况下

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

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

谢谢西蒙娜雷,我也找到了另一个优雅的功能组合解决方案。

像这样。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM