ariel
ariel

Reputation: 16150

Why Object.create doesn't clone properties as expected?

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

Answers (2)

rsmeral
rsmeral

Reputation: 576

Answer

Why doesn't Object.create clone properties as expected?

Because Object.create isn't supposed to clone properties.

JavaScript objects are tricky

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:

  • Property accessor – 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.

Why does JSFiddle print it differently than Chrome?

Apparently, JSFiddle's implementation of console enumerates inherited properties, whereas Chrome's console implementation doesn't.

Upvotes: 3

Morten
Morten

Reputation: 84

Runs as expected even in console. You just have to extend the Object.

enter image description here

Upvotes: 2

Related Questions