Reputation: 16150
If I type this into console:
var x = {a: 1};
var y = Object.create(x);
console.log(y);
It shows {}
. But if I run it in fiddle it shows {a: 1}
, which is the expected result. Also here:
var x = {a: 1};
var y = Object.create(x);
console.log(y);
So what is going on?
Upvotes: 2
Views: 75
Reputation: 576
Why doesn't Object.create clone properties as expected?
Because Object.create
isn't supposed to clone properties.
If we look at the documentation of Object.create
, it says:
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
Besides its own properties, each object in JavaScript also inherits properties from its prototype.
Now, the tricky part is – inherited properties are only visible in some cases. For example:
y.a
or y['a']
– ✅ sees inherited properties
console.log(y.a); // outputs 1
Object.keys
, Object.values
, Object.entries
– ❌ doesn't see inherited properties
console.log(Object.keys(y)); // outputs []
These concepts are much more comprehensively covered in Enumerability and ownership of properties.
For a more thorough explanation of prototypes, see Object prototypes.
Apparently, JSFiddle's implementation of console
enumerates inherited properties, whereas Chrome's console
implementation doesn't.
Upvotes: 3
Reputation: 84
Runs as expected even in console. You just have to extend the Object.
Upvotes: 2