get
:將定義在物件的 method 用 property 取值的方式做呼叫。set
:將定義在物件的 method 用 property 存值的方式做呼叫。
使用 get
或 set
的好處是,可以在每次存取 property 的時候,執行一些邏輯或 side effect。
class Person {
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
// Getter for first name
get firstName() {
return this._firstName;
}
// Setter for first name
set firstName(newFirstName) {
this._firstName = newFirstName;
}
// Getter for last name
get lastName() {
return this._lastName;
}
// Setter for last name
set lastName(newLastName) {
this._lastName = newLastName;
}
// Getter for full name
get fullName() {
return `${this._firstName} ${this._lastName}`;
}
}
const person1 = new Person('John', 'Doe');
console.log(person1.fullName); // Output: "John Doe"
person1.firstName = 'Jane';
console.log(person1.fullName); // Output: "Jane Doe"