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和lastName8 [this.firstName, this.lastName] = name.split(" ");9 }10};// 访问getter(不需要括号)11console.log(person.fullName);// 触发setter12person.fullName = "Jane Smith";// Getter现在返回更新后的名字13console.log(person.fullName);运行结果
John Doe Jane Smith
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 JavaScript 代码中需要输入的符号及其出现次数。
.× 10"× 8;× 6(× 5)× 5{× 5}× 5,× 4=× 3:× 2