如何在构造函数中使用setter



我不知道如何在构造函数中使用setter,我想在设置字段之前验证字段,我想通过构造函数来做到这一点,所以我要做的是:

class Person {
private _name: string;
constructor(newName: string) {
// this.name(..) gives error, This expression is not callable. Type 'String' has no call signatures.
this._name = this.name(newName);
}
get name(): string {
return this._name;
}
set name(newName: string) {
if (newName.length > 2 && newName.length < 10) {
this._name = newName;
} else {
throw new RangeError("Must be between 2 and 10 characters of length");
}
}
}

所以我可以简单地做:

const George = new Person("George")
不应显式调用Setter(和getter(。当您为属性分配值时(即,当您执行this.name = value;时(,setter会自动调用:
class Person {
private _name = '';
constructor(newName: string) {
this.name = newName
}
get name(): string {
return this._name;
}
set name(newName: string) {
if (newName.length > 2 && newName.length < 10) {
this._name = newName;
} else {
throw new RangeError("Must be between 2 and 10 characters of length");
}
}
}
console.log(new Person('George').name);

最新更新