Sometimes, we want to override JavaScript’s toString() function to provide meaningful output for debugging.
In this article, we’ll look at how to override JavaScript’s toString() function to provide meaningful output for debugging.
How to override JavaScript’s toString() function to provide meaningful output for debugging?
To override JavaScript’s toString() function to provide meaningful output for debugging, we can add the Symbol.toStringTag
method into our class.
For instance, we write
class Person {
constructor(name) {
this.name = name;
}
get [Symbol.toStringTag]() {
return "Person";
}
}
let p = new Person("Dan");
Object.prototype.toString.call(p);
to create the Person
class that has the Symbol.toStringTag
which returns the string that’s logged when we call toString
on a Person
instance.
Then we create the p
Person
instance.
Finally, we call Object.prototype.toString.call
with p
to call toString
using the overridden toString
method we created.
Conclusion
To override JavaScript’s toString() function to provide meaningful output for debugging, we can add the Symbol.toStringTag
method into our class.