Javascript objects parsed vs created

javascript, json

Solution

The main difference is that `p` is an object, that is an instance of `Person` while `p2` is a "plain" object, that is just an instance of `Object`.

When is this 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 is not defined

Or:

console.log(p.constructor) //Person
console.log(p2.constructor) //Object

2) using the `instanceof` operator:

p instanceof Person //true
p2 instanceof Person //false

3) everything that has to do with inheritance

All three points can essentially be traced back to the prototype chain, that looks like this for both ways:

p --> Person --> Object

p2 --> Object

Now, since you have this constructor function I would suggest you always use it, because it can get quite messy if you mix `Person` objects with plain objects. If you really just want an object, that has a `Name` property, you would be fine in both ways, but as soon as it gets a little bit more complex, you can run into severe problems.

Problem

What is the practical difference between `p` and `p2` objects here: ``` var Person = function(name) { this.Name=name; } var p = new Person("John"); var p2 = JSON.parse('{"Name":"John"}'); ``` What are the cases when I would better create `new Person()` and copy values from parsed JSON, rather than use that parsed JSON object as I would use the instance of `Person`? PS. Let's say I got JSON string from WebSocket and I will have to parse it anyway.

Original source