javascript 如何删除只设置JS?

ttisahbt  于 2023-01-01  发布在  Java
关注(0)|答案(2)|浏览(125)

我刚刚读过JavaScript中的getter/setter。
正如MDN上的文档所写:
如果你想删除setter,你可以只delete它:
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?**

谢谢!

qxgroojn

qxgroojn1#

为此,请使用Object.defineProperty(与{set: undefined}一起使用):

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

这将仅删除设置器。

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"
vx6bjr1n

vx6bjr1n2#

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";

好多了。不是吗?

相关问题