Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Object.create does not work in node.js

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?

like image 274
wbars Avatar asked Oct 02 '14 10:10

wbars


1 Answers

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.

like image 131
thefourtheye Avatar answered Sep 24 '22 17:09

thefourtheye