0

Refering to this post : Why console.log(obj) show structure of obj instead of return value of toString()

I have figured out that this piece of code will log the value returned by toString() method of Obj

class Obj {
  constructor(){
    this.prop = 'a property';
  }
  toString(){
    return 'This is toString method of an instance of Obj and I have ' + this.prop;
  }
}

console.log(new Obj() + "");

Is there another approach to do that ?

Community
  • 1
  • 1
Jose Hermosilla Rodrigo
  • 3,513
  • 6
  • 22
  • 38

2 Answers2

0

With new ES6 template literals, this becomes simplest :

class Obj {
  constructor(){
    this.prop = 'a property';
  }
  toString(){
    return 'This is toString method of an instance of Obj and I have ' + this.prop;
  }
}

console.log(`${new Obj()}`);

${new Obj()} will call toString method of Obj.

Jose Hermosilla Rodrigo
  • 3,513
  • 6
  • 22
  • 38
  • That's actually longer than what the OP had, and much less convenient. – Bergi Jun 01 '16 at 02:20
  • Thank you for your comments. But I don't understand why is this not convenient? – Jose Hermosilla Rodrigo Jun 01 '16 at 03:19
  • It does look much stranger and more complicated than the simple string concatenation, at least in my eyes. It's less convenient to type and to visually parse. It would be fine if there was any text in the template literal, but like this it is not a good solution. – Bergi Jun 01 '16 at 03:25
  • You're right with this. I just discover this behaviour with objects by chance experiencing with ES6 features and I wanted to post here, so i didn't add more flourishes to the string logged. I thought this was strange too. But I think, once known, is not so strange. "Calling an object in a template literal returns the string of its toString() method". – Jose Hermosilla Rodrigo Jun 01 '16 at 03:42
  • 1
    I didn't mean that the behaviour of objects in template strings is strange (it's quite reasonable given how they work), but that I find it strange to see them used for this. – Bergi Jun 01 '16 at 03:45
  • Sorry for misundestand you! So I'll take into account that and I'll avoid to use the template literals for doing this. Thank you for clarify my mind. =) – Jose Hermosilla Rodrigo Jun 01 '16 at 03:51
0

Objects have string version set '[object Object]' as default; You can change it by overriding the toString method (in a class for example). If you pass console.log(new Obj()) it will simply output the object with its properties (because you passed Object type to the console.log). If you add '' + ... it will convert the object to the string, because it has higher precedence. And how do you convert object to string? Well, by calling its toString() method, which you can override and output some text like in your code.

Azamantes
  • 1,435
  • 10
  • 15