简体   繁体   English

Chrome开发人员工具中控制台中对象之间的差异

[英]DIfference between objects in console on chrome developer tools

When I print one of my objects (created via ajax calls) to the console I am getting back: 当我打开我的一个对象(通过ajax调用创建)到控制台时,我回来了:

Object
discreet: Array[2]
range: Array[2]
__proto__: Object

But when I manually create the object I am correctly getting back: 但是当我手动创建对象时,我正在回复:

Object {range: Array[2], discreet: Array[2]}
discreet: Array[2]
range: Array[2]
__proto__: Object

Could someone explain to me the difference between these two objects, and why I am unable to access the properties of the first object? 有人可以向我解释这两个对象之间的区别,以及为什么我无法访问第一个对象的属性?

Edit: The first object is being created by: 编辑:第一个对象是通过以下方式创建的:

var obj = {}

$http.get('/discreet').then( function(data) { obj.discreet = data } );
$http.get('/range').then( function(data) { obj.range = data } );

print(obj);

The second I am hand crafting: 第二个我手工制作:

var obj = { range: [1,2], discreet: [1,2] }
print(obj);

This is a classic case of misunderstanding asynchronous programming. 这是误解异步编程的经典案例。 Here's what you need to know: 这是你需要知道的:

  1. JavaScript is single-threaded, so it can only do one thing at a time. JavaScript是单线程的,因此它一次只能做一件事。

  2. The callback function in .then attached to $http.get is asynchronous -- it is not immediately executed. 在回调函数.then连接到$http.get是异步-它不是立即执行。 Instead, it is queued up for execution whenever the Ajax request returns from the server. 相反,只要Ajax请求从服务器返回,它就会排队等待执行

  3. Asynchronous callbacks cannot run until the current function has completed. 在当前函数完成之前,异步回调无法运行。 They cannot commandeer the execution thread, but must patiently wait for the current function to finish using it. 它们不能执行执行线程,但必须耐心等待当前函数完成使用它。

Thus, when print(obj); 因此,当print(obj); is run, obj has not yet been assigned any properties because neither asynchronous callback has had a chance to run. 运行时, obj尚未分配任何属性,因为两个异步回调都没有机会运行。

If you do see properties when you expand the Object that is produced on the console, it's because Chrome is lazy about supplying properties for objects printed in the console. 如果在展开控制台上生成的Object确实看到了属性,那是因为Chrome在为控制台中打印的对象提供属性方面很懒惰。 It will only ask the object for its properties when you actually click to expand it (at which time the callbacks will have completed). 当您实际单击以展开它时,它将仅询问对象的属性(此时回调将完成)。

The first one is simply being print ed before the xhr response has returned, so the object is empty at the time it is logged. 第一个是在xhr响应返回之前简单地进行print ,因此对象在记录时是空的。

The second one is logged after it has been populated. 第二个在填充后记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM