0

Having this code:

var Person = function(_name){
     this.name = _name;
}

Person.prototype.surname = 'Jiménez';

What's the difference between this.name and Person.prototype.surname, what changes when inherited? what's the difference then when:

var newPerson = new Person('Carlos');
R01010010
  • 5,670
  • 11
  • 47
  • 77
  • Both are different properties. While the property "name" exists on the object newPerson, the property "surname" is inherited from the prototype. – Aravind Nov 10 '14 at 17:13
  • Read some good book like "Javascript: The definitive guide" to learn Javascript. – Aravind Nov 10 '14 at 17:22
  • Explained in detail here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Nov 10 '14 at 23:39

1 Answers1

0

The difference is where the property is defined, .name is defined on the actual newPerson object while .surname is defined on newPerson's prototype object. if you were to create 2 Person objects the two will share the same .surname property but each will have its own .name property.

notice that once you assign a different value to .surname on an object like this

newPerson.surname = 'some name';

you actually defines a completely new property on the object. the only way to go back to view the prototype value is to do

delete newPerson.surname;

Barak
  • 1,148
  • 7
  • 13
  • so for the this.name there isn't a chain? – R01010010 Nov 10 '14 at 18:28
  • .name property does not exists in newPerson's prototype chain so it is not part of the chain. this.name by itself is a string primitive so it doesn't have a prototype chain. other than primitives and the base Object in javascript every object has a prototype chain (many of which just points to Object) – Barak Nov 12 '14 at 21:08