🔸getter/setter

JSclassdefinition ⟩ getters/setters

class User {

    constructor(name) {
        this.name = name;        // ⭐ invokes "setter"❗
    }

    // ⭐ getter: access `this.name`
    get name() {
        return this._name;
    }

    // ⭐ setter: set `this.name` (this.name = ...)
    set name(value) {
        
        // guard length >= 4
        if (value.length < 4) {
            log("name too short."); return;
        }
        
        this._name = value;    // private property
    }
    
}

// test code
let user = new User('Mary');

// ⭐ invokes "setter": 
user.name = 'Joe';             // "name too short."

// ⭐ invokes "getter": 
log(user.name);                // "Mary"

Archive

const {log} = console;

/* -------------- new object -------------- */

const expr = 'foo';

const obj = {

  // obj.log             ↱ ⭐️ 注意:有 ","
  log: ['example','test'],

  // ⭐️ getter (obj.latest)
  get latest() {
    return this.log[this.log.length - 1];
  },

  // ⭐️ getter (obj.foo)
  get [expr]() { return 'bar' }        // ⭐️ computed property name

};

/* -------------- existing object -------------- */

const o = {a: 0};

// ⭐️ o.b                  ↱ ⭐️ property name
Object.defineProperty(o, 'b', { 
    get: function() { return this.a + 1 } 
});

// ⭐️ p.name (= name)
//    ↱ ⭐️ (same) object passed in ↰
const p = Object.defineProperties({ }, {
//  ↱ ⭐️ property name
  name: {   //                                    ↱ ⭐️ 注意:有 ","
    set(name) { this._name = name.toLowerCase(); },
    get()     { return this._name; }
  },
});

p.name = 'MoLLy BroWn';      // ⭐️ setter				

/* -------------- class definition -------------- */

class MyArray extends Array {

  // ⭐️ instance getters         ↱ ⭐️ 注意:沒有 ","
  get first() { return this[0] }                // arr.first
  get last() { return this[this.length - 1] }   // arr.last

  // ⭐️ static getter
  static get foo() { return 'foo' }             // ⭐️ MyArray.foo
}

/* -------------- log -------------- */
const arr = new MyArray('a', 'b', 'c', 'd');

[
    obj.latest,             // 'test'
    obj.foo,                // 'bar'

    o.b,                    // 1
    p.name,                 // "molly brown"

    arr.last,               // "d"
    arr.push('e'),          // 5 (⭐️ new length)
    arr.last,               // "e"
    MyArray.foo,            // 'foo'

].forEach(x => log(x));

Last updated