The properties of objects in JavaScript can be divided into data properties and accessor properties. Accessor properties include getter and setter methods

  • getterreadThe function called when the object property
  • setterwriteThe function called when the object property

Accessor properties cannot be defined directly and must be defined using Object.defineProperty().


var person = {
    _age: 16.kind: 'young'
}

// Object.defineProperty(obj, prop, descriptor)
// obj specifies the object on which attributes are to be defined.
// prop Specifies the name of the property to define or modify.
Attribute descriptor to be defined or modified.
Object.defineProperty(person, "age", {
    / / the getter function
    get() {                     //ES6 syntax get() is equivalent to get: function()
        return this._age;
    },
    / / setter function
    set(newValue) {
        if (newValue < 18) {
            this.kind = 'young'
        } else {
            this.kind = 'adult'
        }
        this._age = newValue
    }
})
// When reading the property value of the object, the get() method is called, returning the value of Person._age
console.log(person.kind)      // Output: young
console.log(person.age)      // Output: 16
<18 change kind to young, >18 change kind to Adult
person.age = 24
console.log(person.kind)   // Output: adult
console.log(person.age)    // Output: 24



Copy the code

So the getter and the setter are basically monitoring the age of an object person and calling the getter when the age property is read; The setter function is called when age is written.