Let’s consider this code:
(function(){
var a = {"id": "1", "name": "mike", "lastname": "ross"};
var b = JSON.parse('{"id": "1", "name": "mike", "lastname": "ross"}');
var c = Object.create({"id": "1", "name": "mike", "lastname": "ross"});
document.write(typeof(a) + "</br>");
document.write(typeof(b) + "</br>");
document.write(typeof(c) + "</br>");
})();
Questions
- Which are the differences between the three assignments?
- Do the objects a, b and c exactly overlap?
- If yes, why? If no, why?
Please add references to your answers.
Demo.
aandbare effectively identical (they have the same properties, with the same values, in the same places).cis completely different. You can see a clear difference if you log the objects to the console instead of printing limited info to the page:cis the one on the right. It’s created an object with no own properties. The properties you specified are actually on theprototypeofc. The reason for this is that the first argument toObject.createis theprototypeof the object to be created.Note that you could use
Object.createto get the same effect – just passObject.prototypeas the first argument: