简体   繁体   English

为什么我的 getter、setter 在 Typescript 中不起作用?

[英]Why does my getter,setter not working in Typescript?

I want to check my password`s length before assigning value to the password.我想在为密码赋值之前检查密码的长度。 If value's length is less than 3 it has to throw an error.如果值的长度小于 3,则必须抛出错误。 But it is not returning anything.但它没有返回任何东西。 Why?为什么?

I have a Department class and ITDepartment subclass.我有一个部门 class 和 ITDepartment 子类。

class Department {
    static currentYear = 2022
    departmentName:string
    empNum:number
    employees :string[] = []
    constructor(public name:string,nums:number, 
        employees:string[]){
        this.departmentName =name
        this.empNum = nums
        this.employees = employees
    }


}

class ITDepartment extends Department {
orginizingDate : number
 private password :number

 public get pass (){
    return this.password
 }


 public set pass (value:number){
    if(value.toString().length < 3){
        throw new Error ('The password is not safe ')
    }
     this.password = value
 }

constructor(empNum:number,employees:string[],orginizingDate :number,password:number){
    super("IT",empNum,employees)
    this.orginizingDate = orginizingDate
    this.password = password
}
printInfo(){
    console.log("The Department " + this.departmentName  +" has " + this.empNum +" employers and orginized in " +this.orginizingDate)
}

addEmployee(employee: string): void {
    if(employee === "Adam"){
        return
    }
    this.employees.push(employee)
}
}   

let it = new ITDepartment(52,[],2000,22)

this.password = password won't go through the setter named pass . this.password = password不会通过名为pass的设置器 go 。 Furthermore, you aren't actually comparing the length, but the value itself.此外,您实际上并不是在比较长度,而是在比较值本身。

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

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