为什么javascript对象在Chrome,Firefox,Safari的控制台中显示不同的值? [英] Why does javascript object show different values in console in Chrome, Firefox, Safari?

查看:440
本文介绍了为什么javascript对象在Chrome,Firefox,Safari的控制台中显示不同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Chrome的JavaScript控制台是否懒于评估数组?

考虑这个javascript:

Consider this javascript:

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

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

在Firefox的firebug中,这显示了我的预期:

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

Object { bar=1111}
1111

Object { bar=2222}
2222

然而,在Safari和Chrome的控制台中显示:

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.

这是浏览器的怪癖吗?或者是我缺少的面向对象的javascript的一个基本方面?

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

推荐答案

在Chrome中(WebKit,所以也是Safari), console.log 使用对象参数调用记录对象引用。单击并打开对象选项卡后,内部保持不变(可能是各种缓存)并且不再与最初引用的对象相关(因此,如果在稍后阶段对象发生更改,则不会反映)。然而,在此之前,对象仍然是未缓存的。因此,当您多次登录对象然后打开每个已记录的对象时,它们都指向内存中的同一对象,其值是最新更新的对象。

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.

简单的解决方法是获取对象的非对象值的任何方法,因此任何序列化方法(例如 console.log(JSON.stringify(foo)); )。

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

这篇关于为什么javascript对象在Chrome,Firefox,Safari的控制台中显示不同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆