In developer console (Mozilla, Chrome, nvm) this code work as expected:
var proto = {x: 3};
var obj = Object.create(proto);
So obj
will be {x: 3}
But in node.js i get {}
Why?
In Node.js, when you use console.log
to print something, it uses util.inspect
to get the string representation of the object. Quoting from console.log
doc,
If formatting elements are not found in the first string then
util.inspect
is used on each argument.
When we check the util.inspect
we understand that, unless it is called with showHidden
property set to true
, it will not include the object's non-enumerable properties.
But wait, non-enumerable properties are entirely different from properties inherited via prototype chain. So, even util.inspect
cannot see them. Then how do we get to see the inherited properties?
The only way to get the objects inherited via prototype chain is by using a for..in
loop. Quoting from for..in
's MDN doc,
The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor's prototype (properties closer to the object in the prototype chain override prototypes' properties).
You can confirm that like this
var proto = {
x: 3
};
var obj = Object.create(proto);
for (var key in obj) {
console.log(key);
}
// x
Since console.log
is not part of the ECMA Standard specification, various implementations can implement it as they like. So, the browsers would be internally using the for..in
loop to gather all the inherited properties whereas node guys decided not to do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With