我可以在对象属性上使用装饰器吗?

时间:2017-12-17 21:28:34

标签: javascript typescript decorator

通常我会像这样应用装饰器:

getSupportActionBar()

还有一些方法可以将它用于普通对象而不是类:

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

1 个答案:

答案 0 :(得分:5)

是的,但不太实际。您可以为对象的属性调用装饰器,但不能像装饰类及其内容一样。

鉴于以下装饰者:

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

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

deco(testObj, 'testMethod');

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

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

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

相关问题