【问题标题】:Overriding property getter from accessor decorator覆盖访问器装饰器的属性获取器
【发布时间】:2020-07-24 14:31:33
【问题描述】:

我有一些这样的代码:

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。

【问题讨论】:

  • 装饰器return不应该是新的描述符吗?
  • 根据文档和打字,没有。不适用于属性/访问器装饰器
  • 显然我在阅读文档时搞砸了,这些文档区分了属性装饰器(应用于普通字段)和访问器装饰器。不同之处在于,我错过了包含当前属性描述符的第三个参数

标签: typescript decorator typescript-decorator propertydescriptor


【解决方案1】:

我错过的是,对于 accessor 装饰器,您有一个 PropertyDescriptor 作为第三个参数传入。

执行以下操作就足够了:


propertyDescriptor.get = () => 'new value';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-18
    • 2018-11-26
    • 1970-01-01
    • 2012-11-22
    • 2014-03-11
    • 2015-07-07
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多