Scandinave
Scandinave

Reputation: 1438

Add class attribute with decorator

I try to use a decorator to add some method or property to an annotated class.

This is my decorator :

export default function Component(params) {
    return function decorator(target) {
        target.template = params.template;
        console.log(target, params.template);
    }
}

I used it this way :

@Component({
    template: template
})
export default class App {}

But when I use this class :

app.template // undefined;

Any idea?

Upvotes: 1

Views: 1599

Answers (1)

idmitme
idmitme

Reputation: 929

You are modifying class object itself, i.e.

App.template // your template is here

and you just defined a static property for App class in this case.

In order to set template for class instances you should use:

target.prototype.template = params.template;

(Good example that classes are actually just syntactical sugar over constructor functions and prototype-based inheritance).

Also, I think this article about combining mixins and decorators might be helpful.

Upvotes: 2

Related Questions