Avatar ·

TypeScript中的Getter和Setter:如何正确使用get和set?

大家好!我刚开始学习TypeScript,是从JavaScript转过来的。我好像理解类,但怎么也搞不懂getter和setter(get和set)。 我有一个简单的User类,想在其中存储名字和姓氏,并在访问fullName字段时获取它们的组合。我写了这样的代码: ```typescript class User { firstName: string; lastName: string; get fullName(): string { return `${this.firstName} ${this.lastName}`; } } const user = new User(); user.firstName = "Иван"; user.lastName = "Петров"; console.log(user.fullName); // "Иван Петров" - 有效! ``` 但后来我尝试为fullName创建一个setter,以便可以用一个字符串设置名字和姓氏: ```typescript class User { firstName: string = ''; lastName: string = ''; get fullName(): string { return `${this.firstName} ${this.lastName}`; } set fullName(value: string) { const parts = value.split(' '); this.firstName = parts[0]; t