Setter and getter of JS class attribute

You can use the GET and SET keywords inside the “class” to set the save and accessor functions for a property and intercept the access behavior of that property.

class A {
  constructor () {
    this._a = 'a'
  }
  set a (val) {
    if (Object.prototype.toString.call(val)  !== '[object String]') {
      this._a = 'error'
    } else {
      this._a = val
    }
  }
  get a () {
    return this._a
  }
}

let obj = new A()
console.log(obj.a) // a
obj.a = 123
console.log(obj.a) // error


Read More: