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.
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 Person
s derived using the constructor.
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.
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