JS getters and setters inside a class?

Kuba Orlik picture Kuba Orlik · Feb 4, 2014 · Viewed 13.6k times · Source

I'd like to create a class in JS that uses native getters and setters. I know I can create getters/setters for objects, like so:

var obj = {
    get value(){
        return this._value;
    },
    set value(val){
        this._value = val;
    }
}

I also know that I can use this.__defineGetter__ inside a class/function, but MDN says that using __defineGetter__() etc is discauraged.

Is there any better way to add getters and setters to js class than:

function class(){
};

class.prototype = {
   get value(){
        //....

}

?

Answer

user1160006 picture user1160006 · Jan 10, 2019

2019: Hooray for ES6!

class Person {
    
    get name() {
        return this._name + '!!!'
    }

    set name(newValue) {
        this._name = newValue
    }

    constructor(name) {
        this._name = name
    }
}

const me = new Person('Zach')
console.log(me.name)            // Zach!!!

me.name = 'Jacob'
console.log(me.name)            // Jacob!!!

// Of course, _name is not actually private.
console.log(me._name)           // Jacob