Node js overrides toString

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 ie calls my function console.log (Lion); //doesn't call my function. Prints { code: 0, name: 'jack' } 

doesn't call toString by default?

+6
source share
4 answers

Came to this on google before finding an answer that I liked, here is what I ended up doing:

You can use inspect , and v8 (chrome / nodejs) will use this from console.log () calls:

 function Foo() {} Foo.prototype.inspect = function() { return "[object Foo]"; } console.log(new Foo()); 
+6
source

Not always. Browsers such as Chrome allow you to validate an object (for debugging purposes) using console.log ().

Try the following:

 console.log (''+Lion); 
+6
source

I was also interested in how to do this when I saw how beautifully Immutable.js displays objects:

 var Immutable = require('immutable'); var map = Immutable.Map({ a: 1, b: 2 }); console.log(map); // Map { "a": 1, "b": 2 } 

After some scanning of the source code, I found that they pulled it out by adding the toString and inspect methods to the prototype object. Here is the basic idea, more or less:

 function Map(obj) { this.obj = obj; } Map.prototype.toString = function () { return 'Map ' + JSON.stringify(this.obj); } Map.prototype.inspect = function () { return this.toString(); } 

The presence of the toString and inspect methods means that the object will be correctly disabled in the node (using inspect ), and if necessary it will be correctly formatted as a string (using toString ).

EDIT: this only applies to node, browsers will still log out. If you do not want this, first convert it to a string, either by calling toString , or by concatenating it using another string: console.log('' + map) .

+2
source

No. Adding something to the prototype makes it available, but that does not mean that it will be called simply because you create an instance of the object to which it belongs.

For instance:

 function foo() { var bar = 123; } foo.prototype.show_bar = function() { console.log(this.bar); } var x = new foo(); // does not log anything x.show_bar(); // logs 123 

I think your confusion thinks console.log() automatically trying to convert its parameter to a string. This is not true; it can output arrays, objects, functions, etc.

+1
source

All Articles