Accessors Methods通常翻译为'存取器方法”,也可以叫做'访问器方法”、 '获取器方法”、 '设置器方法”。它们是一种常见的代码实现方式,用于获取和设置对象的属性。
示例代码:
class Person { constructor(name, age) { this._name = name; this._age = age; }
get name() { return this._name; }
set name(newName) { this._name = newName; }
get age() { return this._age; }
set age(newAge) { if (newAge < 0) { console.log("Age cannot be negative") } else { this._age = newAge; } } }
const person = new Person("Alice", 32); console.log(person.name); // Alice person.name = "Bob"; console.log(person.name); // Bob console.log(person.age); // 32 person.age = -3; // Age cannot be negative console.log(person.age); // 32