I am trying to override the default toString method for my objects, Here is the code and the problem:
function test (){
this.code = 0;//later on I will set these
this.name = "";
}
test.prototype.toString= function(){
return this.name + "\t"+ this.code +" \t "+this.anotherFunction();
}
console.log (Lion.toString()); //works correct i.e. calls my function
console.log (Lion); //doesn't call my function. Prints { code: 0, name: 'jack' }
doesn't toString get called by default?
Came across this on google before finding an answer I liked, here is what I ended up doing:
You can use inspect
and v8(chrome/nodejs) will use that from console.log() calls:
function Foo() {}
Foo.prototype.inspect = function() {
return "[object Foo]";
}
console.log(new Foo());
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