Search code examples
javascriptgetter-setterdelete-operator

How to remove only setter JS?


I've just read about getters/setters in JavaScript.

As the documentation on MDN writes:

If you want to remove the setter, you can just delete it:
delete o.current;

This code removes the setter...

var object = {
  something: "",
  get property() {
    return this.something
  },
  set property(value) {
    this.something = value
  }
}

object.property+="1"
object.property+="2"
object.property+="3"
object.property+="4"

console.log(object.property) //"1234"

delete object.property

console.log(object.property) //undefined

... but the getter (with the same name) too.

I need to use the same name to use the += operator.

So the question:

Is there a way in JS to remove a setter, but keep the getter?

Thanks!


Solution

  • Use Object.defineProperty (with {set: undefined}) for this purpose:

    Object.defineProperty(object, "property", {set: undefined})
    

    This will remove only the setter.

    const object = {
      something: "",
      get property() {
        return this.something
      },
      set property(value) {
        this.something = value
      }
    }
    
    object.property += "1"
    object.property += "2"
    object.property += "3"
    object.property += "4"
    
    console.log(object.property) //"1234"
    
    Object.defineProperty(object, "property", {set: undefined}) //delete setter
    
    console.log(object.property) //"1234"
    
    object.property += "5" //setter missing, fails silently
    
    console.log(object.property) //still "1234"