Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON literals and Javascript objects. I am confused

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

  1. Which are the differences between the three assignments?
  2. Do the objects a, b and c exactly overlap?
  3. If yes, why? If no, why?

Please add references to your answers.

Demo.

like image 733
Alberto De Caro Avatar asked Oct 11 '12 14:10

Alberto De Caro


2 Answers

a and b are effectively identical (they have the same properties, with the same values, in the same places). c is completely different. You can see a clear difference if you log the objects to the console instead of printing limited info to the page:

enter image description here

c is the one on the right. It's created an object with no own properties. The properties you specified are actually on the prototype of c. The reason for this is that the first argument to Object.create is the prototype of the object to be created.

Note that you could use Object.create to get the same effect - just pass Object.prototype as the first argument:

var d = Object.create(Object.prototype, { 
    "id": { "value": 1 }, //values are 'property descriptors'
    "name": { "value": "mike" }
    //etc...
});
like image 200
James Allardice Avatar answered Nov 08 '22 17:11

James Allardice


a and b result in "indentical" objects (in the same way that {a:1} abd {a:1} are identical).

JSON.parse parses the input JSON string, and outputs the parsed value. In this case, an object.

c is different. Object.create creates a new object with the prototype set to the first argument. You can verify that c.__proto__.id is equal to 1 (and unavailable in the first two cases).

At the first sight, all of the three methods result in the "same" object: Reading the property id gives 1 in all cases. In the third case, this result is caused by prototype inheritance. This offers a possible feature:

var x = Object.create({id:1});
x.id = NaN;
console.log(x.id);
// NaN
delete x.id;
console.log(x.id);
// 1 - The old value is back :)
// ( for x = {id: 1};, the old value would be gone! )
like image 33
Rob W Avatar answered Nov 08 '22 18:11

Rob W