1

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?     
user2864740
  • 60,010
  • 15
  • 145
  • 220
  • With `prototype` you're basically putting inside the Prototype of Person. With `this` you're putting in instance level. To elaborate on this, with every new instance you can have different property with `this` but not on `prototype`. You have one `global` (for the lack of better word) property for that `constructor`. – shriek Aug 11 '14 at 01:26
  • `.this` is a syntax error. Please make sure to write accurate titles/questions. – user2864740 Aug 11 '14 at 01:27
  • Your code using the prototype doesn't make much sense. Maybe the following answer can help you understand what prototype is and how to use it: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Aug 11 '14 at 02:19

1 Answers1

2

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.

alex
  • 479,566
  • 201
  • 878
  • 984
  • If the prototype changes were made outside of the constructor, what would be the difference? – J369 Mar 22 '18 at 17:52