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
Please add references to your answers.
Demo.
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:
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...
});
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! )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With