Skip to content Skip to sidebar Skip to footer

Javascript Logging Object With Mutating State

This JavaScript code... var o = {}; console.dir(o); o.foo = 'bar'; console.dir(o); ...results in the same interactive tree output shown twice: This issue is discussed as a bug he

Solution 1:

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 inref)
                r[i] = deep_copy(ref[i]);
    }
    elseif(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));

Post a Comment for "Javascript Logging Object With Mutating State"