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 con
Solution 1:
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.
Solution 2:
They have a constructor
property, that does not point to Object
, but to Ressource
in that case.
Solution 3:
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
.
Post a Comment for "What Is The Difference Between JavaScript's Object Literals And Object That Appears To Be Named When Console Logged?"