0

Resources I've read

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

Object.create not working as expected

I have a simple script

const defaults = {
    allowInputStyleChange: true
};

var entry = Object.create(defaults);

console.log(JSON.stringify(defaults));
console.log(JSON.stringify(entry));

This results in

{"allowInputStyleChange":true}
{}

I was expecting

{"allowInputStyleChange":true}
{"allowInputStyleChange":true}

Am I understanding how to implement it wrong?

mrid
  • 5,782
  • 5
  • 28
  • 71

2 Answers2

1

However, if you do:

console.log(entry.allowInputStyleChange); // true
console.log(entry.hasOwnProperty('allowInputStyleChange')); // false

The problem you have is that JSON.stringify only shows the enumerable own property of an object.

So Object.create is working according to what you're expecting, it's just that JSON.stringify does not show the prototype

Axnyff
  • 9,213
  • 4
  • 33
  • 37
1

Object.create() creates a new object with the passing object's prototype.

JSON.stringify() serializes the own enumerable properties of the object. Since, entry does not have it's own property, it returns {}

To get the properties of defaults included in the JSONString, you can use Object.assign():

const defaults = {
    allowInputStyleChange: true
};

var entry = Object.assign({}, defaults);

console.log(JSON.stringify(defaults));
console.log(JSON.stringify(entry));
Mamun
  • 66,969
  • 9
  • 47
  • 59