Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js overriding toString

Tags:

node.js

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?

like image 644
kousha Avatar asked Feb 15 '14 23:02

kousha


Video Answer


1 Answers

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());
like image 155
Jacob Hacker Avatar answered Dec 21 '22 01:12

Jacob Hacker