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 ...