[英]What is the difference between JavaScript's object literals and object that appears to be named when console logged?
I have noticed there are times when I console.log an object, I get the object literal and sometimes its seems what is console.logged is prefixed with a name. 我注意到有时候我在console.log中有一个对象,我得到了对象的文字,有时它似乎是什么是console.logged以前缀为名称。
For example, If I console.log an object before sending it to the server I get: 例如,如果我在将对象发送到服务器之前调试对象,我得到:
{id: 18, date: "2017-09-13T21:59:59.999Z"...etc}
but when I console the same log returned as a promise from a server call, I get: 但是当我通过服务器调用控制返回的相同日志作为承诺时,我得到:
Resource {id: 18, date: "2017-09-13T21:59:59.999Z"...etc}
What causes this differences? 是什么导致这种差异? and What are the differences between what seems to be two different representations of an object?
什么似乎是一个对象的两个不同表示之间的差异?
它们有一个constructor
属性,它不指向Object
,但在这种情况下指向Ressource
。
The console is giving you hints, it doesn't always log stuff as is. 控制台给你提示,它并不总是按原样记录。
For example: 例如:
var Cat = function (name) {
this.name = name;
}
var paws = new Cat('paws');
console.log(paws);
will act similar to Resource
in your example. 在您的示例中将与
Resource
类似。 The console is hinting at the constructor
. 控制台暗示了
constructor
。
The latter is an instance of a named class: 后者是命名类的实例:
class Resource {
constructor() {
this.id = ...;
this.date = ...;
}
}
Or a named constructor: 或者命名的构造函数:
function Resource() {
this.id = ...;
this.date = ...;
}
In both cases, the class or constructor in instantiated with the new
keyword, but class
is the newer ES6 syntax. 在这两种情况下,使用
new
关键字实例化的类或构造函数,但class
是较新的ES6语法。
console.log(new Resource())
Your first example is simply a plain object with no constructor. 您的第一个示例只是一个没有构造函数的普通对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.