Why does javascript object show different values in console in Chrome, Firefox, Safari? [duplicate]

Possible Duplicate:
Is Chrome's JavaScript console lazy about evaluating arrays?

Consider this javascript:

var foo = {bar : 1111};
console.log(foo);
console.log(foo.bar);

foo.bar = 2222;
console.log(foo);
console.log(foo.bar);

In Firefox's firebug, this shows what I would have expected:

Object { bar=1111}
1111

Object { bar=2222}
2222

However, in Safari and Chrome's console it shows:

Object { bar=2222}
1111

Object { bar=2222}
2222

In other words, the object is showing the wrong attributes in the console when print-dumped, but the correct value if a specific attribute is printed.

Is this a quirk of the browsers? Or a fundamental aspect of object oriented javascript that I am missing?

Answers:

Answer

In Chrome (WebKit, so Safari also), console.log calls with object arguments log an object reference. Once the object tab is clicked and opened, the internals remain constant (presumably a cache of sorts) and are no longer related to the object initially referred to (so if at a later stage the object changes, this will not be reflected). However until that point the object remains "uncached". So when you log an object multiple times then open each logged object, they all point to the same object in memory, whose value is the most current updated one.

It's a well known "issue", although the behaviour is a result of a design decision (see comments on the first link), and so isn't considered a bug by the dev team.

Easy workarounds are any means to get a non-object value of the object, so any serialisation method (e.g. console.log(JSON.stringify(foo));).

https://bugs.webkit.org/show_bug.cgi?id=35801
http://code.google.com/p/chromium/issues/detail?id=44720
http://code.google.com/p/chromium/issues/detail?id=50316

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.