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

javascript - add and delete smart getter programmatically

我正在尝试以编程方式从对象中添加和删除(出于缓存目的)getter。我要像这样添加 getter:

Object.defineProperty(obj, 'text', {
  get: getter
})

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');
}

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

编辑:

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

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
  }
})

What I've found is, that this is the prototype of the Object rather than the instance...

不在您显示的代码中,除非您以奇怪的方式调用它。

一种方法是使用 Object.defineProperty 重新定义 属性。

例如,如果您在一次性对象上执行此操作:

var obj = {
  get notifier() {
    var value = Math.random();
    console.log("Getter called");
    Object.defineProperty(this, "notifier", {
      value: value
    });
    return value;
  }
};
console.log("First use");
console.log(obj.notifier);
console.log("Second use");
console.log(obj.notifier);

或者如果不是一次性的:

function Maker() {
}
Object.defineProperty(Maker.prototype, "notifier", {
  get: function() {
    var value = Math.random();
    console.log("Getter called");
    Object.defineProperty(this, "notifier", {
      value: value
    });
    return value;
  },
  configurable: true
});
var obj = new Maker();
console.log("First use");
console.log(obj.notifier);
console.log("Second use");
console.log(obj.notifier);


我一直坚持上面的 ES5 级别的东西,因为你似乎没有使用任何 ES2015+ 功能。

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

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


除此之外,如果您对从原型对象继承的属性有疑问,您