javascript - 以编程方式添加和删除智能 getter

Joh*_*nes 2 javascript getter defineproperty

我正在尝试以编程方式从对象中添加和删除(用于缓存目的)getter。我正在添加一个这样的吸气剂:

Object.defineProperty(obj, 'text', {
  get: getter
})
Run Code Online (Sandbox Code Playgroud)

obj.text 只应在第一次访问时对其进行评估,并将计算出的值缓存以供后续调用使用。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get展示了如何实现这样的智能 getter:

get notifier() {
  delete this.notifier;
  return this.notifier = document.getElementById('bookmarked-notification-anchor');
}
Run Code Online (Sandbox Code Playgroud)

但是,我无法delete this.text在我的getter函数中使用。我发现的是,这this是对象的原型而不是实例 - 对吗?如果是这样,我如何删除实例的 getter 并将其替换为计算值?

编辑:

根据评论,getter 和 object 看起来像这样:

var obj = {}
obj.value = '2018-04-21T12:00:00Z000'

Object.defineProperty(obj, 'text', {
  get: function () {
    delete this.text  // doesn't seem to work

    if (this.value == null) return ''
    var text = this.value.split('T')[0].split('-').reverse().join('.')
    this.text = text
    return text // return this.text ends in Maximum call stack size exceeded
  }
})
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

您需要使属性可配置,以便您可以删除它:

var obj = {value: '2018-04-21T12:00:00Z000'};

Object.defineProperty(obj, 'text', {
  get: function () {
    delete this.text

    if (this.value == null) return ''
    var text = this.value.split('T')[0].split('-').reverse().join('.')
    console.log("updating")
    this.text = text
    return text
  },
  configurable: true
//^^^^^^^^^^^^^^^^^^
});
console.log("first access");
console.log(obj.text);
console.log("second access");
console.log(obj.text);
Run Code Online (Sandbox Code Playgroud)


除此之外,如果您对从原型对象继承的属性有问题,则无法删除它,但需要使用defineProperty来隐藏它

  • @Johannes:如果你的意思是`var obj = {get notifier() { ... }};`,那么访问器定义为`configurable: true`:https://tc39.github.io/ecma262/#sec-方法-定义-运行时-语义-属性定义评估。默认值专门用于`defineProperty`/`defineProperties`(以及规范中未特别提及的其他地方)。 (2认同)