Object Properties Configuration

Accessor Property

getters and setters

  • get: a function without arguments, that works when a property is read,
  • set: a function with one argument, that is called when the property is set,
  • enumerable: same as for data properties,
  • configurable: same as for data properties.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let user = {
name: "John",
surname: "Smith",

get fullName() {
return `${this.name} ${this.surname}`;
},

set fullName(value) {
[this.name, this.surname] = value.split(" ");
}

};

alert(user.fullName); // John Smith
  • We don’t call user.fullName as a function, we read it normally.
  • e.g. user.fullName and user.fullName = "Wayne Zhang"
文章目录
  1. 1. Accessor Property
    1. 1.1. getters and setters