Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method I can override on a JavaScript object to control what is displayed by console.log?

I'm thinking in particular of Chrome, though Firebug would be interesting to. I've tried toString() and valueOf(), but neither of those seem to be used. Interestingly, if I take a function it'll display the function definition - but then if I add a toString() method it will show null!

var a = function(){};
console.log(a); // output: function (){}
a.toString = function(){ return 'a'; };
console.log(a); // output: null
a.valueOf = function(){ return 'v'; };
console.log(a); // output: null

Any ideas?

like image 975
agnoster Avatar asked Jun 02 '10 19:06

agnoster


People also ask

Can we override console log?

log. To override a console method, we just need to redefine how the method is executed. You'll need to wrap your code to prevent the access of other functions to the private (original) method.

Can we override toString method in JavaScript?

Overriding toString for custom objectsYou can create a function to be called in place of the default toString() method. The toString() function you create should return a string value.

How do you wrap a console log?

Another way to console. log your variables is to simply place your mouse cursor on them and then wrap them on the line below with Ctrl+Alt+W + Down or the line above with Ctrl+Alt+W + Up .

What is the console in JavaScript?

The JavaScript console is a command line interface in your browser that can execute snippets of code. When that code snippet is designed to interact with the webpage you are currently on, result can happen that might not have been possible otherwise.


3 Answers

There's no way I know of. Your best bet will be to define a toString() method on the object you want to log and then call it, either directly or indirectly:

var o = {};
o.toString = function() {
    return "Three blind mice";
};

console.log("" + o);
console.log(o.toString());
like image 73
Tim Down Avatar answered Oct 02 '22 14:10

Tim Down


Just for future readers, there is now a way to do exactly what is asked here.

For the solution please read this duplicated post:

adjust console.log behaviour of custom object

like image 26
mhombach Avatar answered Oct 02 '22 14:10

mhombach


You can do this in Chrome nowadays with a devtools custom formatter. They don't seem to be officially documented anywhere, and aren't enabled by default -- so you have to enable them in (Dev Tools Settings) > Console > Enable Custom Formatters. But then you can add a custom formatter for your object:

class CustomClass {
    constructor (foo, bar) { this.foo = foo; this.bar = bar; }
}

window.devtoolsFormatters = (window.devtoolsFormatters || []).concat([{
    header: (obj) => {
        if (obj instanceof CustomClass) {
            return ['div', {}, `CustomClass(${obj.foo}, ${obj.bar})`];
        } else {
            return null; // fall back to default formatter
        }
    },
    hasBody: () => true, // if the user can expand to get more info
    body: (obj) => {
        return ['div', {},
            ['span', {style: 'display: block; font-weight: bold'}, 'CustomClass'],
            ['span', {style: 'display: block; margin-left: 2em'}, `foo: ${obj.foo}`],
            ['span', {style: 'display: block; margin-left: 2em'}, `bar: ${obj.bar}`],
        ];
    }
}]);

A few words of warning:

  • You must return a JsonML ([tag-name, attrs, children...]) list from the formatter. If you return an invalid JsonML or a bare string, it will either fail silently or throw an error.
  • The formatter must have a header() and hasBody() function, and if hasBody() returns true, must have a body() function as well. Otherwise your formatter will be either silently ignored or throw an error.
  • A lot of element types aren't supported. I was only able to get div and span to work; p, strong, and other elements all failed. But you can emulate them with CSS.
  • The window.devtoolsFormatters array is null by default, but I added the check because extensions may already add their own custom formatters.

You can find a bit more information here: https://docs.google.com/document/d/1FTascZXT9cxfetuPRT2eXPQKXui4nWFivUnS_335T3U/preview

like image 40
vgel Avatar answered Oct 02 '22 16:10

vgel