๐Ÿ”ธgetter/setter

JS โŸฉ class โŸฉ definition โŸฉ 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