Mutated State JavaScript Object

This javascript code ...

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

... leads to displaying the same interactive tree: 2 Two objects with foo: "bar" shown
This issue is seen as a bug here in the Stack Overflow section , registered as Chromium bug and WebKit (and I suppose it is in another place).

I understand the reason for the implementation, that it is, but it greatly complicates the debugging of objects with state preservation (without using an interactive debugger). What strategy do you use for logging in situations where you need to see different object states in each log call? JSON.stringify() ? Is there a console method for serialization that can be used?

+4
source share
1 answer

I would solve this by making a "deep copy" of what you are registering and passing the copy to console.dir (). Something like this works very 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 do not want to worry about something like that, then using JSON.stringify is a great workaround and will not be much slower if it is native in the browser.

 console.dir(JSON.parse(JSON.stringify(o)); 
+2
source

Source: https://habr.com/ru/post/1339662/


All Articles