简体   繁体   中英

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.

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. The console is hinting at the 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.

console.log(new Resource())

Your first example is simply a plain object with no constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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