Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript objects parsed vs created

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.

like image 396
Anri Avatar asked Aug 13 '13 09:08

Anri


2 Answers

The difference between p and p2 is that the internal prototype of p2 is the Object.prototype, whereas the prototype of p is the Person.prototype; for the p you can add common methods or attributes to all Person objects by adding methods to the Person.prototype.

Thus you could have the JSON format to have fields such as "givenName", "surname" "title", and by using the new Person approach, you could have a method:

Person.prototype.getFullName = function () {
    return this.title + " " + this.givenName + " " + this.surname;
}

that is readily available all Persons derived using the constructor.

like image 148

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.

like image 40
basilikum Avatar answered Sep 22 '22 08:09

basilikum