skip to Main Content

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?

2

Answers


  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

    Login or Signup to reply.
  2. 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));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search