In ES5 style javascript, to override the toString
method I would simply do the following:
function myFunction() {
}
myFunction.prototype.toString = function() {
return "My amazing function";
};
var myAmazingFunc = new myFunction();
console.log(myAmazingFunc);
In my current code I use ES6 and my object is now a class (which essentially is a function).
class MyAwesomeClass {
// awesome code goes here
}
What I have tried to do to override the toString
method are the following:
class MyAwesomeClass {
toString() {
return "Awesome";
}
}
And also
class MyAwesomeClass {
// awesome code goes here
}
MyAwesomeClass.prototype.toString = function() {
return "Awesome";
};
Also without the prototype
- but still it does not seem it's being called.
How is this possible in ES6 class?
We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.
When you print an object, by default the Java compiler invokes the toString() method on the object. So by overriding the toString() method, we can provide meaningful output.
There will not be enough information about state or properties of object. So, whenever you use or print a reference variable of type in which toString() method is not overrided, you will get an output like above. You will not get what the object actually has in it.
This actually does work:
class MyAwesomeClass {
toString() {
console.log("toString called");
return "Awesome";
}
}
console.log(new MyAwesomeClass() + "!!!");
There must be something wrong with how you're testing (hint: console.log
doesn't trigger toString
).
If you're looking for a way to customize the console.log
output, this is only possible in node.js (https://nodejs.org/api/util.html#util_custom_inspection_functions_on_objects), by adding a custom inspect
method. This feature is deprecated though as of node 10.
The console.log()
will not call the toString()
method for you... you also need to use the ${}
class MyAwesomeClass {
toString() {
console.log("toString called");
return "Awesome";
}
}
let e = new MyAwesomeClass();
console.log(`${e}`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With