0

I've recently changed from Java backend to JS frontend. We use a backbone like object structure (at least that's what my colleagues told me) and I wondered if there is a way to override toString() (e.g. should be called from console.log).

This is what our models looks like

// namespace
var De = {};
De.Ppasler = {};

De.Ppasler.Model = (function () {

/** @constructor */
function Model(param) {
   var self = this;

   self.public = function() {
    // do sth public
    console.log("public", private());
   };

   function private() {
    // do sth private
    return "private";
   }
   
   // this is what I would have done in Java
   self.toString = function() {
    return "[object Model]";
   }
 }

 return Model;
}());

var model = new De.Ppasler.Model();
model.public();
console.log(model);

Add toString Model does not work.

I've also tried this one:

Model.prototype.toString and self.prototype.toString but this leads to Errors

I can't make sure model is defined and I want to avoid an undefined-check, before calling toString directly for loggin purpose.

Community
  • 1
  • 1
ppasler
  • 3,579
  • 5
  • 31
  • 51
  • 1
    See this: http://stackoverflow.com/q/36215379/2333214. `console.log` is not part of standard. You'd be better of overriding `console.log`/ writing your own log function that invokes `toString`/specific method you have defined – T J May 12 '17 at 08:50
  • Thanks for the hint, I would have guessed 100% that `console.log` is a standard function... I am spoiled from Java I guess :) – ppasler May 12 '17 at 08:53
  • This really looks like a [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you trying to achieve here? – Emile Bergeron May 12 '17 at 12:10
  • @EmileBergeron as I thought this is a common approach, I didn't question it. My intention is to log the "object" in a meaningful way. As I can't mek sure its defined, I dont want to call `model.toString()`. – ppasler May 12 '17 at 12:27
  • `console.log` with most browsers tools is intelligent and it let you explore objects directly in it. – Emile Bergeron May 12 '17 at 12:30
  • hmm, that's a point. But I am just curious, would it be possible, although the standard might be better? – ppasler May 12 '17 at 12:41
  • `console.log` doesn't necessarily calls `toString` but `alert` does for example. – Emile Bergeron May 12 '17 at 13:06
  • I see, could you provide the last 3 comments as an answer and I will accept it... confusing JS :) – ppasler May 12 '17 at 13:09

1 Answers1

1

Most browsers tools provide an intelligent console.log that let you explore objects directly, so there's no need to override toString.

console.log demo with class

Even if you would override toString on your object, most browsers implementation of console.log don't call toString on the passed objects.

Something like alert would do what you expect.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129