2

I'm trying to understand JavaScript prototype and when I attempted coding this I get an error:

function Person(firstname, last name) {
  this.firstname = firstname;
  this.lastname = lastname;
}

var A = new Person('John', 'Doe');

A.prototype.name = 'Toby';

I get an error stating cannot set property 'name' of undefined. Can't i assign a property on it's prototype of Object A. This is just a simple exercise to get an understanding of prototypes

1 Answers1

3

Objects don't have a prototype property (unless you create one). You usually only assign to the prototype property of constructors:

function Person(firstname, lastname) {
  this.firstname = firstname;
  this.lastname = lastname;
}

Person.prototype.name = 'Toby';

var A = new Person('John', 'Doe');

// A.name === 'Toby';
Paul
  • 139,544
  • 27
  • 275
  • 264