开发者

JavaScript logging object with mutating state [duplicate]

开发者 https://www.devze.com 2023-02-11 10:51 出处:网络
This question already has answers here: How can I make console.log show the current state of an object?
This question already has answers here: How can I make console.log show the current state of an object? (12 answers) Closed 8 years ago. 开发者_C百科

This JavaScript code...

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

...results in the same interactive tree output shown twice:

JavaScript logging object with mutating state [duplicate]

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?


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));
0

精彩评论

暂无评论...
验证码 换一张
取 消