# getter/setter

[JS](../../..) ⟩ [value](../..) ⟩ [object](..) ⟩ [property]() ⟩ getter/setter

{% hint style="success" %}
([es5](../../../feature/es5 "mention"))

an accessor property (not a data property) that has a getter and/or a setter method.

```javascript
// defining "accessor properties"

// method 1:
let obj = {
    // data property
    _value: 0,
    // accessor property (pair of methods)
    get prop() { return this._value },
    set prop(value) { this._value = value },
};

// method 2:
Object.defineProperty(obj, 'prop', {
    get() { ... },         // getter
    set(value) { ... },    // setter
});

obj.prop;            // getting obj.prop
obj.prop = value;    // setting obj.prop
```

:u6307: <mark style="color:yellow;">**synonyms**</mark>： "<mark style="color:purple;">**accessor property**</mark>"
{% endhint %}

{% tabs %}
{% tab title="👥 相關" %}
* class [getter-setter](../../class/member/getter-setter "mention")
* [arr.last](../../builtin/arr/ext/arr.last "mention")
* [es6](../../../feature/es6 "mention") (shorthand method names)
* [helpers](../../../../appendix/gas/app/helpers "mention")
{% endtab %}

{% tab title="💈範例" %}
* replit：[define properties](https://replit.com/@pegasusroe/object-define-properties#index.js)

```javascript
// object
const obj = { _name: 'john doe' };
const _age = 38;

// 🔸 using `Object.defineProperty()`
Object.defineProperty(obj, 'age', {

    // shorthand method names (ES2015)
    // -------------------------------
    // ⭐️ 注意：這裡沒有 ":" 冒號❗️
    //   ↑
    get() { return _age; },
    set(value) { _age = value; },

    enumerable: true,
    configurable: true
});

// 🔸 using `Object.defineProperties()`
Object.defineProperties(obj, {

    // ⭐️ data property
    isMale: {
        value: true,
        writable: true,
    },

    // ⭐️ accessor property
    name: {
        get() { return this._name },
        set(value) { this._name = value },
    },

});

// test
obj.name = 'Joe';    // "setter" called

obj.name,            // 'Joe'
obj.isMale,          // true
obj.age,             // 38
```



* <mark style="color:yellow;">**more examples ...**</mark>
  * [window.name](../../../scope/global/object/window/window.name "mention")
  * [\_\_proto\_\_](../extend/inheritance/__proto__ "mention")
{% endtab %}

{% tab title="📗 參考" %}
* [ ] [javascript-the-definitive-guide](../../../../master/ref/javascript-the-definitive-guide "mention") ⟩ 6.10.6 Property Getters & Setters
{% endtab %}

{% tab title="📘 手冊" %}
* [ ] [Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions) ⟩ [getter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)
* [ ] [Object.defineProperty()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)
{% endtab %}
{% endtabs %}
