【问题标题】:can I use decorators on object properties?我可以在对象属性上使用装饰器吗?
【发布时间】:2018-05-31 06:36:17
【问题描述】:

通常我这样应用装饰器:

class SpecialMethods {
    @Deco
    static someMethod() {
    }
}

还有什么方法可以将它与普通对象而不是类一起使用:

const SpecialMethods = {
    @Deco
    someMethod: () => {}
}

【问题讨论】:

  • 你指的是哪些装饰器?提案的?
  • 什么是abstract class?这看起来不像 JavaScript。
  • @Bergi 抱歉,我目前正在大量使用打字稿。我已删除摘要

标签: javascript typescript decorator


【解决方案1】:

是的,但它不是很实用。您可以为对象的属性调用装饰器,但与装饰类及其内容的方式不同。

给定以下装饰器:

const TestDecorator = (at: string) => {
    return function (target: any, prop: string, descriptor?: PropertyDescriptor) {
        console.log(`decorated at ${at}}`);
    }
}

将在类中如下使用:

class TestClass {
    @TestDecorator('class method')
    public testMethod() { }
}

但是,它不能以与上述相同的方式应用于属性:

const testObj = {
    @TestDecorator('property method')
    testMethod: () => { }
};

要解决此问题,您可以在属性中调用装饰器。

首先你必须声明你的对象及其所有属性:

const testObj = {
    testMethod: () => { }
};

我的装饰器需要一个柯里化值:

const deco = TestDecorator('property method');

现在您必须为testObj 中的属性手动调用deco 装饰器:

deco(testObj, 'testMethod');

如果您在装饰器中需要 propertyDescriptor(它不在 OP 中),您还必须手动提供它:

deco(testObj, 'testMethod', Object.getOwnPropertyDescriptor(testObj, 'testMethod'));

这是TS playground。检查控制台中的输出。

【讨论】:

  • 为什么不传递属性描述符?
  • @Bergi 在此示例中不需要这样做。这仅显示了如何为object 调用装饰器,我没有在装饰器中操作任何东西。
  • 嗯,是的,但这在很大程度上取决于 OP 的实际装饰器所做的事情,所以最好给出一个通用的解决方案,或者至少声明它只是一个简化的例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 2023-03-16
  • 2018-05-02
  • 2019-02-02
  • 1970-01-01
  • 2015-12-20
相关资源
最近更新 更多