overexchange
overexchange

Reputation: 1

When does Decorator code execute?

For the below given syntax,

import validator from "./ZipCodeValidator";

that imports dictionary of objects from ZipCodeValidator.ts to name validator in current name space, at build/bundling time,

where ZipCodeValidator.ts looks like:

export class C {
    @f()
    @g()
    method() {}
}

Are decorators(f & g) annotated to methods in ZipCodeValidator.ts executed on running import statement(above) at build/bundling time?

Upvotes: 1

Views: 1343

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161457

Decorators are always executed when the class declaration is executed. Since most class declarations are often in the top-level scope of a module, that can mean that they run when the code is executed, but there's nothing stopping you from having a class declaration inside of another function, in which case the decorators would only run when that function was called.

In your specific case, the decorator factory f() would run during the declaration to return the actual decorator function, and then the class declaration will call the decorator.

The decorator function itself could always mutate the method to call some custom logic when method is called, but the decorator itself is long done by then.

Upvotes: 5

Related Questions