来自访问器装饰器的重写属性获取器

我有一些类似这样的代码:

function changeProperty(prototype: Object,propertyKey: string) {
  Object.defineProperty(prototype,'extra',{
    get: () => 'added'
  });

  const existing = Object.getOwnPropertyDescriptor(prototype,propertyKey);
  Object.defineProperty(prototype,propertyKey,{
    get: () => 'pass'
  });
}

class Test {
  @changeProperty
  get original() { return 'fail'}
}

// Write TypeScript code!
const appDiv: HTMLElement = document.getElementById('app');
const x = new Test() as any;
appDiv.innerHTML = `original: ${x.original}<br/>extra: ${x.extra}`;

https://stackblitz.com/edit/typescript-j8s1bq

我观察到extra属性已成功添加,但是我无法覆盖/覆盖/删除现有属性。

我不知道为什么会这样。

如果使用类装饰器,则可以使用相同的技术来覆盖getter。

xcmk27 回答:来自访问器装饰器的重写属性获取器

我想念的是对于 accessor 装饰器,您传入了PropertyDescriptor作为第三个参数。

执行以下操作就足够了:


propertyDescriptor.get = () => 'new value';
本文链接:https://www.f2er.com/2461849.html

大家都在问