Reputation:
Could someone please explain the differences of the two code below using a constructor function. They both give the same results. Does one have an advantage over the other?
function Person(){
Person.prototype.name = "Nicholas";
Person.prototype.age = 29;
}
var person1 = new Person();
var person2 = new Person();
person1.name = "Greg";
alert(person1.name); //"Greg" from instance
alert(person2.name); //"Nicholas" from prototype
VERSUS
function Person(){
this.name = "Nicholas";
this.age = 29;
}
var person1 = new Person();
var person2 = new Person();
person1.name = "Greg";
alert(person1.name); // "Greg" from instance
alert(person2.name); // "Nicholas" from Person Object?
Upvotes: 1
Views: 46
Reputation: 490213
They're doing something different.
The first one is assigning the same details to the prototype on each invocation of the constructor. These details will be shared by every object created via this constructor. This is definitely not what you should be doing. Generally, only methods should be added to the prototype, and definitely not within the constructor's body. It should happen outside of the constructor (it's just running pointless code needlessly and will be confusing to other developers).
The second, those properties are local to the constructed object returned, which is this
in that context. This is the correct way of having instance properties.
Upvotes: 2