Creating a Custom Decorator
Learn to create a custom decorator for objects.
We'll cover the following
Using toString()
method on an object
Suppose we have a Person
class that has a few fields. Let’s create an instance, called peter
, for the class and invoke the toString()
method on it, like so:
console.log(peter.toString());
Problem
The output of this call will be
[object Object]
This is disappointing if we were hoping to get a glimpse of the fields and their values. If we printed the instance without .toString()
, we would have seen all the fields, but maybe that’s too much.
Solution
It would be great to dictate what toString()
should return, without having to write it for each class we create. What if we could decorate classes with a ToString()
decorator? Seems like a nice idea.
ToString
decorator
The ToString()
decorator, which we will design and implement here, will take an array of fields/properties to exclude. In the decorator function, we will inject a toString()
method into the class’s prototype. This toString()
method will iterate over all the keys of the object and create a string representation while excluding any field/property that’s in the exclude array.
Since decorators are really functions, we should start by writing a ToString()
decorator factory as we did for the @Component
decorator in the previous lesson.
Get hands-on with 1400+ tech skills courses.