There are two different types of properties: data properties and accessor properties.
- Data properties contain a value.
- Accessor properties don’t contain a value but instead define a getter function and a setter function.
const person1 = {
_name: "Nicholas",
get name() {
console.log("Reading name");
return this._name;
},
set name(value) {
console.log("Setting name to %s", value);
this._name = value;
}
};
console.log(person1.name); // "Reading name" then "Nicholas"
person1.name = "Greg";
console.log(person1.name); // "Setting name to Greg" then "Greg"
This example defines an accessor property called name
. There is a data property called _name
that contains the actual value for the property.
The leading underscore is a common convention to indicate that the property is considered to be private, though in reality it is still public. The syntax used to define the getter and setter for name looks a lot like a function but without the function keyword. The special keywords get
and set
are used before the accessor property name, followed by parentheses and a function body.