class的 get、set修饰符

class 中的属性前标注了 get set 即被称为 **访问器属性**。其他的都是**数据属性**

访问器属性数据属性有一些区别,例如:

  1. 访问器属性可以让你在读取或修改对象的属性时执行一些验证、计算或日志记录等操作,而数据属性不能。
  2. **访问器属性可以让你直接操作对象的属性,而不需要调用方法**,这样可以使代码更简洁和清晰。
  3. 访问器属性可以让你实现一些伪属性,也就是说,你可以定义一个没有实际存储值的属性,而是通过 get 和 set 方法来动态地计算或返回值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 使用访问器属性
class Person {
#name; // 私有字段
constructor(name) {
this.#name = name;
}
get name() {
// 获取器方法
return this.#name.toUpperCase(); // 返回大写的名字
}
set name(newName) {
// 设置器方法
if (newName.length > 0) {
// 验证新名字是否为空
this.#name = newName;
} else {
console.log("Invalid name");
}
}
}

// 使用数据属性
class Person {
#name; // 私有字段
constructor(name) {
this.#name = name;
}
getName() {
// 普通方法
return this.#name.toUpperCase(); // 返回大写的名字
}
setName(newName) {
// 普通方法
if (newName.length > 0) {
// 验证新名字是否为空
this.#name = newName;
} else {
console.log("Invalid name");
}
}
}

可以看到,使用访问器属性的类可以直接用<u>person.name</u>来获取或设置名字,而使用数据属性的类需要用<u>person.getName()</u><u>person.setName()</u>来调用方法。这就是访问器属性和数据属性的一个区别。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!