Decorator factories

In order to allow for decorators to accept parameters, we need to use what is known as a decorator factory. A decorator factory is simply a wrapper function that returns the decorator function itself. As an example of this, consider the following code:

function decoratorFactory(name: string) { 
    return function (constructor : Function ) { 
        console.log(`decorator function called with : ${name}`); 
    } 
} 

Here, we have defined a function named decoratorFactory that accepts a single argument, named name, of type string. This function simply returns an anonymous decorator function that takes a single argument named constructor of type Function. The anonymous function (our decorator function) logs the value of the name parameter to the console.

Note here how we have wrapped the decorator function within the decoratorFactory function. This wrapping of a decorator function is what produces a decorator factory. As long as the wrapping function returns a decorator function, this is a valid decorator factory.

We can now use our decorator factory, as follows:

@decoratorFactory('testName') 
class ClassWithDecoratorFactory { 
     
} 

Note how we can now pass a parameter to the decorator factory, as shown in the usage of @decoratorFactory('testName'). The output of this code is as follows:

decorator function called with : testName

There are a few things to note regarding decorator factories. Firstly, the decorator function itself will still be called by the JavaScript runtime with automatically populated parameters. Secondly, the decorator factory must return a function definition. Lastly, the parameters defined for the decorator factory can be used within the decorator function itself, as it is in the same scope as the decorator function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.196.184