// 定义一个对象,使用 getter 和 setter 方法来访问和修改属性
class Person {
constructor(name) {
this._name = name; // 使用下划线前缀表示这是一个私有属性
}
// getter 方法,用于获取属性的值
get name() {
return this._name;
}
// setter 方法,用于设置属性的值
set name(newName) {
if (typeof newName === 'string') {
this._name = newName;
} else {
console.log('Name must be a string');
}
}
}
// 创建一个 Person 实例
const person = new Person('Alice');
// 使用 getter 获取属性值
console.log(person.name); // 输出: Alice
// 使用 setter 修改属性值
person.name = 'Bob';
console.log(person.name); // 输出: Bob
// 尝试设置一个非字符串类型的值
person.name = 123; // 输出: Name must be a string
console.log(person.name); // 输出: Bob
上一篇:js i18n
下一篇:js set集合
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站