Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript toString() seems not to be called automatically in NodeJS

The documentation on mozilla.org states: "Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", ..."

Sounds logical: A toString() method will be called. So I defined an own "class" and defined a toString() method:

function DataField(name, dataType)  {
    // ....
}

DataField.prototype.toString = function() {
    return this.type.name + " " + this.name;
}

I instantiate an object like this:

var dataField = new DataField("myint", DataType.INTEGER);

I try to output the object respectively the string representation of the object in NodeJS:

console.log(dataField);
console.log("" + dataField);
console.log(dataField.toString());

The first output differs from the other ones. The first one will give some kind of JSON.stringify() representation of the object. toString() is not called automatically as I'd expect it to be. The second and third output will result in exactly what I'd expect:

INTEGER myint

So I'm a bit confused. That means that toString() will not automatically be called though the explanation of mozilla.org suggests. Is this a regular behaviour in NodeJS or did I missinterpret the explanation on mozilla.org or am I missing something else here?

You might think: Well, then let's just call toString() explicitely if necessary and everything is fine. But there is some inconvenience with that. If I create an array of objects and use console.log() to ouput that array, no toString() will be called. Which means: The output generated is useless. This would mean that if I store objects with explicite implementations of toString() within an array in a container object I will have to implement toString() of the container object in a very specific and incovenient way: I must write code to explicitely create a string representations of any array of objects contained in the container object myself. Of course I could do that, but I would intuitively assume a toString() method to be called automatically therefor eliminating such need for explicite implementations.

Regarding NodeJS it seems that finding information is not that easy on this specific problem. So if you know about this topic any help is appreciated. The question is: What is the most elegant way to create a (human readable) string representation of a data model (= a data container object containing lists of other data objects)?

like image 235
Regis May Avatar asked Dec 30 '25 05:12

Regis May


1 Answers

In Node.js, console.log calls util.format, which does not call toString().

like image 68
SLaks Avatar answered Jan 01 '26 18:01

SLaks