我不知道如何在构造函数中使用 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")
答案 0 :(得分:1)
不应显式调用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);