json - Javascript objects parsed vs created -
what practical difference between p
, p2
objects here:
var person = function(name) { this.name=name; } var p = new person("john"); var p2 = json.parse('{"name":"john"}');
what cases when better create new person()
, copy values parsed json, rather use parsed json object use instance of person
?
ps. let's got json string websocket , have parse anyway.
the main difference p
object, instance of person
while p2
"plain" object, instance of object
.
when difference important?
1) accessing prototype properties:
var person = function(name) { this.name=name; } person.prototype.getname = function () { return this.name; }; p.getname() //works fine p2.getname() //error since getname not defined
or:
console.log(p.constructor) //person console.log(p2.constructor) //object
2) using instanceof
operator:
p instanceof person //true p2 instanceof person //false
3) has inheritance
all 3 points can traced prototype chain, looks both ways:
p --> person --> object p2 --> object
now, since have constructor function suggest use it, because can quite messy if mix person
objects plain objects. if want object, has name
property, fine in both ways, gets little bit more complex, can run severe problems.
Comments
Post a Comment