Reputation:
When I create an object using literal syntax, printing the object to the console shows the object foo
and the p
property.
foo = {};
foo.p = 42;
console.log(foo);
console.log(foo.p);
Outputs:
{ p: 42 }
When I use Object.create() syntax, printing the object with console.log shows an empty object.
bar = Object.create({}, { p: { value: 42 } });
console.log(bar);
console.log(bar.p);
Outputs:
{}
42
Why doesn't bar
show the property p
when using console.log()?
Upvotes: 2
Views: 324
Reputation: 1074028
I'm guessing you're using NodeJS for these tests.
The reason is that in your second example (using Object.create
), the p
property is non-enumerable. When I run your examples on NodeJS, I don't see p
in the second example because it's non-enumerable, since properties created via property descriptors such as the one in your second argument to Object.create
default to non-enumerable unless you include enumerable: true
. If I add enumerable: true
to it, I see p
in the second example, too.
What you see will vary depending on what environment you're using. For instance, in Chrome's devtools, I see p
in both examples even when p
isn't enumerable. But when outputting to a non-interactive console, I guess they decided to only show enumerable properties.
Upvotes: 4