Property getters and setters

有 2 種類型的屬性,一般的屬性為資料屬性,另一種為訪問屬性,基本用來獲取、設定值,看起來跟一般屬性一樣。

Getters and setters

// syntax
let obj = {
  get propName() {
    // getter, the code executed on getting obj.propName
  },

  set propName(value) {
    // setter, the code executed on setting obj.propName = value
  }
};

// 用已有的資料添加 fullName 屬性
let user = {
  name: "John",
  surname: "Smith",

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

alert(user.fullName); // John Smith
// 不用函式的方式呼叫 get,使用一般屬性呼叫得到值

// 改變 fullName 的值,要用 set
let user = {
  name: "John",
  surname: "Smith",

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

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

// set fullName is executed with the given value.
user.fullName = "Alice Cooper";

alert(user.name); // Alice
alert(user.surname); // Cooper

// 一個屬性只能有一個類型,如果屬性用 get、set 定義,就不是資料屬性。
// If there’s a getter – we can read object.prop, otherwise we can’t.
// If there’s a setter – we can set object.prop=..., otherwise we can’t.
// 我們不能刪除訪問屬性

Accessor descriptors

訪問屬性沒有 value、writable。

  • 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.

Smarter getters/setters

Using for compatibility

Last updated

Was this helpful?