JavaScript 的 Getter和Setter

等级 4286 次按键

Getter和Setter提供对对象属性的受控访问。

JavaScript 代码

// 创建一个带有getter和setter的对象
1const person = {
// 普通属性
2 firstName: "John",
3 lastName: "Doe",
// Getter: 像普通属性一样访问的计算属性
4 get fullName() {
5 return `${this.firstName} ${this.lastName}`;
6 },
// Setter: 当赋值给fullName时运行
7 set fullName(name) {
// 将分割的名字解构到firstName和lastName
8 [this.firstName, this.lastName] = name.split(" ");
9 }
10};
// 访问getter(不需要括号)
11console.log(person.fullName);
// 触发setter
12person.fullName = "Jane Smith";
// Getter现在返回更新后的名字
13console.log(person.fullName);

运行结果

John Doe
Jane Smith
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 JavaScript 代码中需要输入的符号及其出现次数。

  • .× 10
  • "× 8
  • ;× 6
  • (× 5
  • )× 5
  • {× 5
  • }× 5
  • ,× 4
  • =× 3
  • :× 2

JavaScript 等级 4 的更多代码示例

← 返回 JavaScript 打字练习