Reputation: 3432
const object = {
name: 'Andrew',
getName() {
return this.name
}
}
class ObjectClass {
constructor(name) {
this.name = name
}
getName() {
return this.name
}
}
const object2 = new ObjectClass('Andrew')
console.log(object) // Object {name: "Andrew", getName: function getName()}
console.log(object2, 'object2') // ObjectClass {name: "Andrew", constructor: Object}
I've used codesandbox for creating this code and I get there next responses , I'm little bit confused , because I thought that object
and object2
will be the same . {}
thought that it is the same as new Object()
Upvotes: 2
Views: 1728
Reputation: 690
When you are using a class, the class methods go to the prototype chain, which you can access with the Object.getPrototypeOf
function or with the __proto__
property, although the latter is not preferable. When you are directly making an object, the function is a property of the object itself, and so it doesn't go to the prototype chain.
Ultimately, the result of this code depends on your console. For example, if you are using the Chrome console, you will be able to see everything from an object's prototype. Clearly, the console you are using doesn't have that feature.
If you need consistent results, don't console.log objects directly. Instead, turn those objects into strings that you can format as needed, and then log those strings.
Upvotes: 1
Reputation: 997
There are characteristics that distinguish simple objects and classes in Javascript, most notably - from your example - is the accessor method you found missing.
According to the docs, "The __proto__
getter function exposes the value of the internal [[Prototype]] of an object".
You can begin logging internals of your class using reflection and __proto__
:
console.log(Object.getOwnPropertyNames(foo).concat(Object.getOwnPropertyNames(foo.__proto__)))
For more details on logging check this question: Get functions (methods) of a class
Upvotes: 0