JS getters and setters inside a class?
getter, getter-setter, javascript, setter
Solution
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
Problem
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(){ //.... } ``` ?