最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - can I use decorators on object properties? - Stack Overflow

programmeradmin1浏览0评论

Normally I apply the decorator like this:

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

Is there also some way to use it with a plain object rather than a class:

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

Normally I apply the decorator like this:

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

Is there also some way to use it with a plain object rather than a class:

const SpecialMethods = {
    @Deco
    someMethod: () => {}
}
Share Improve this question edited Dec 17, 2017 at 21:56 Nicholas Tower 85.5k10 gold badges105 silver badges121 bronze badges asked Dec 17, 2017 at 21:28 ChrisChris 14.3k24 gold badges94 silver badges184 bronze badges 3
  • 1 Which decorators are you refering to? The proposal ones? – Jonas Wilms Commented Dec 17, 2017 at 21:33
  • 1 What's a abstract class? This doesn't look like JavaScript. – Bergi Commented Dec 17, 2017 at 21:42
  • @Bergi Sorry, I am currently working a lot with typescript. I have removed abstract – Chris Commented Dec 17, 2017 at 21:44
Add a ment  | 

1 Answer 1

Reset to default 7

Yes, but its not very practical. You can invoke the decorator for the properties of an object, but not in the same way as you would decorate a class and its content.

Given the following decorator:

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

Would be used as followed in a class:

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

However, it can't be applied the same way as above for a property:

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

To work around this, you can invoke the decorator at the property.

At first you have to declare your object with all its properties:

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

My decorator expects a curried value:

const deco = TestDecorator('property method');

Now you have to manually invoke the deco decorator for the property in testObj:

deco(testObj, 'testMethod');

If you need the propertyDescriptor in your decorator (it is not in the OP), you'll have to manually provide it as well:

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

Here is a TS playground. Check the output in the console.

发布评论

评论列表(0)

  1. 暂无评论