4

This JavaScript code...

var o = {};
console.dir(o);
o.foo = "bar";
console.dir(o);

...results in the same interactive tree output shown twice:
Two objects with foo:"bar" shown
This issue is discussed as a bug here on Stack Overflow, logged as a Chromium bug and WebKit (and I imagine elsewhere).

I understand the implementation reason that this is the case, but it makes debugging stateful objects hard (without using the interactive debugger). What strategy do you use for logging in such situations, where you need to see the differing states of the object in each log call? JSON.stringify()? Is there a console method for serialization that can be used?

Community
  • 1
  • 1
Phrogz
  • 296,393
  • 112
  • 651
  • 745

1 Answers1

2

I would solve this by making a "deep copy" of what you are logging, and passing the copy to console.dir(). Something like this works pretty well:

function deep_copy(ref)
{
    var r;
    var i;

    if(isHash(ref))
    {
        r = {};
        for(i in ref)
                r[i] = deep_copy(ref[i]);
    }
    else if(isArray(ref))
    {
        r = [];
        for(i = 0; i < ref.length; i++)
            r[i] = deep_copy(ref[i]);
    }
    else
    {
        r = ref;
    }

    return r;
}

If you don't want to bother with something like this, then using JSON.stringify is a great workaround and won't be much slower if it's native in the browser.

console.dir(JSON.parse(JSON.stringify(o));
Phrogz
  • 296,393
  • 112
  • 651
  • 745
Yobert
  • 485
  • 5
  • 11
  • +1 for the idea, though you're missing some code (the definition of `isHash` and `isArray`) and this won't work for properties added to existing objects (e.g. a function or regex), or custom properties on arrays. I hadn't considered using stringify/parse to dup an object while retaining the tree view, however. Nice one. – Phrogz Feb 14 '11 at 16:29
  • 2
    One problem with using `stringify` is that it cannot handle circular references. – Phrogz Feb 14 '11 at 19:17
  • True, @Phrogz, though JSON.stringify() will at least crash while my code above will infinite loop! (oh no!) =) – Yobert Mar 22 '12 at 21:07
  • regarding circular references issues with stringify. There are libs that claim to solve that issue. Ex: circular-json, json-stringify-safe, etc. – Josef.B Apr 29 '17 at 01:38