【问题标题】:How to change the property value in a PropertyDecorator?如何更改 PropertyDecorator 中的属性值?
【发布时间】:2019-02-06 18:38:56
【问题描述】:

如何使用DefaultValue 装饰器在我的TestClass 中更改foo 的值?

class TestClass {
  @DefaultValue('bar')
  private foo;
}

export const DefaultValue = (val: any): PropertyDecorator => {
  return (target: any, propertyKey: string | symbol) => {
    // Change the value of the decorated property
    this[propertyKey] = val; // DOESN'T WORK!
  };
}

不起作用:this[propertyKey] = val;

【问题讨论】:

  • Target 是持有该属性的类的原型(但我才刚刚开始学习 javascript/typescript...不是 100% 确定)。

标签: javascript typescript ecmascript-6 typescript-decorator


【解决方案1】:

你不能。

这是因为目前在定义原型成员时没有描述实例属性的机制,也没有办法观察或修改属性的初始化程序。

~TS docs

【讨论】:

  • target上定义一个同名的属性怎么样?
  • 这是一个想法,你能详细说明一下吗?我正在学习 javascript 和 typescript,我真的很困惑 atm。
  • @gremo 你可以只使用TestClass.prototype.foo = "bar",设置target.foo = "bar" 也会这样做
猜你喜欢
  • 1970-01-01
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
相关资源
最近更新 更多