TL ; DR:
Give a class a toString method that returns a string. JavaScript calls it whenever the object becomes text, as in String(tom).
class Cat {
constructor(name) {
this.name = name;
}
toString() {
return "Cat named " + this.name;
}
}
console.log(String(new Cat("Tom"))); // Cat named Tom
Full lesson:
Every object already has a toString method. The default one isn't much use. It gives the same text for every object:
[object Object]
Write a toString method in your class, and it replaces the default. It returns the text that stands for the object.
JavaScript calls it whenever the object becomes a string. String(tom) does that. So do `I have ${tom}` and "I have " + tom.
There is one catch. console.log(tom) alone doesn't call toString. It shows the object's fields instead, like Cat { name: 'Tom' }. Turn the object into a string first.
toString takes no parameters. It must return the text, not print it.
Your task
The Dog class below has a name and an age. Add a toString method to it.
It returns the name, then " is ", the age and " years old". The code at the bottom prints String(rex) and String(bella).
Expected output:
Rex is 3 years old
Bella is 5 years oldFree plan: 30 tutor messages. Premium is unlimited.
