Getter
- 与Java不同,js中的Getter是一种特殊的方法,当你访问对象的属性时,它会自动被调用
- 它通常用于计算或返回一个值,可以在访问对象属性时做一些额外的逻辑处理。
示例:
const person = {
firstName: 'John',
lastName: 'Doe',
// Getter
get fullName() {
return this.firstName + ' ' + this.lastName;
}
};
console.log(person.fullName); // "John Doe"
当你访问person.fullName时,getter会返回firstName和lastName的拼接值
Setter
- Setter 是另一种特殊的方法,当你为对象的属性赋值时,它会自动被调用。
- 它通常用于设置属性时进行一些验证或修改
const person = {
_firstName: '',
_lastName: '',
// Setter
set fullName(value) {
const names = value.split(' ');
this._firstName = names[0];
this._lastName = names[1] || '';
}
};
person.fullName = 'Jane Smith'; // 调用 setter
console.log(person._firstName); // "Jane"
console.log(person._lastName); // "Smith"
当给person.fullName赋值时,setter会被调用,自动将值拆分成firstName和lastName并进行赋值