javascriptconsole.log

How do I override the default console.log() output of an object?


Say in JavaScript I create a simple object:

function MyObj() {
    this.prop = "property";
}

Now if I create an instance of this and the output it to console I see the object representation:

var obj = new MyObj();
console.log(obj);

How can I instead make that output a string?: For example, I would like that the console displays My property value is 'property' rather than [object object].

I've tried using MyObj.prototype.toString, but it doesn't seem to work.


Solution

  • You could hook the browser console, and redefine it afterwards:

    var obj = {
        name: "Joel",
        age: 32,
        toString: function() {
            return this.name + " is " + this.age + " years old.";
        }
    };
    
    var browserConsole = console;
    
    console = {
        log: function(data) {
            if (typeof data === "object") {
                browserConsole.log(data.toString());
            } else {
                browserConsole.log(data);
            }
        }
    }
    
    console.log(obj);