Search⌘ K

Creating a Custom Decorator

Explore how to design and implement a ToString decorator that dynamically adds a toString() method to any JavaScript class. Learn to exclude specific fields from the string output, enabling more controlled and expressive class representations. This lesson helps you practice metaprogramming by leveraging decorators to modify object behavior dynamically.

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