for my below code I want to setup a default toString() method which overrides the inbuilt toString() for this class. But its not working and I get the output "Queue { data: [] }" instead of expected "Hello This is example". I looked at some already discussed similar questions on SO but no help. I also tried on latest version of Chrome and behaviour is same. I have Node 10.13 with Babel 6 (babel-node --presets env,stage-2 queue.js). Looking for some expert opinion here.
class Queue {
constructor() {
this.data = [];
}
toString() {
console.log("Hello This is example");
}
}
const queue1 = new Queue();
console.log(queue1);
You have to trigger the call for .toString()
explicitly or implicitly
console.log(queue1.toString());
console.log(queue1 + "");
console.log([queue1, queue2].join());
And .toString()
has to return the string representation:
toString() { return "..." }
class Queue {
constructor() {
this.data = [];
}
toString() {
return "Hello This is example"; // toString has to return the string representation
}
}
const queue1 = new Queue();
console.log(queue1 + "");
const queue2 = new Queue();
console.log([queue1, queue2].join());
for my below code I want to setup a default toString() method which overrides the inbuilt toString() for this class. But its not working and I get the output "Queue { data: [] }" instead of expected "Hello This is example".
class Queue {
constructor() {
this.data = [];
}
toString() {
console.log("Hello This is example");
}
}
const queue1 = new Queue();
console.log(queue1);
In the above code the toString
method doesn't override the class's toString
method. Why? Because the class's toString
returns a String.
In your code, console.log("Hello This is example");
doesn't return any value. That is the reason you are getting the output: Queue { data: [] }. This is the default output. If you remove the toString
method from your Queue
class, the statement console.log(queue1);
will still print: Queue { data: [] }.
To make the Queue
class object's representation as a string value, you need to code something like this:
toString() {
return "Hello this is an example";
}
To use the toString
in your application you can try the code on any of the lines #2 or #3 below, and it will print: "Hello this is an example".
const queue1 = new Queue();
console.log(queue1); // #2
console.log(queue1.toString()); // #3
Also see this link and Object.prototype.toString().
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