如何只删除 setter JS?

How to remove only setter JS?

我刚刚在 JavaScript 中读到有关 getters/setters 的内容。

正如 documentation on MDN 所写:

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

此代码删除 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

...但是 getter(同名)也是。

我需要使用相同的名称才能使用 += 运算符。

所以问题:

有没有办法在 JS 中删除一个 setter,但保留 getter?

谢谢!

var object = {
  something: "",
  get x() {
    return this.something
  },
  set y(value) {
    console.log(value);
    this.something = value
  }
}
console.log(object.x)
object.y = object.x + "1"
delete object.y
object.y = object.x + "2"


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

delete object.x

console.log(object.x) //undefined

您必须更改 setter 和 getter 的名称。

object.y += "1"

没有意义,因为你回忆起同样的功能,它会变成:

object.y = object.y + "1";

错了

object.y (set) = object.x (get) + "1";

现在好多了。没有?

为此目的使用 Object.defineProperty(与 {set: undefined}):

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

这将仅删除 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"

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"