-5

I'm reading about prototypes, but I can't seem to understand what they do and what the point of having them is. Can anyone create a simple example (ex. collegeStudent object) that will help me understand the basic concepts of prototypes? Thanks!

Jay
  • 159
  • 1
  • 1
  • 10

1 Answers1

1

Let's say you create a function called person:

function person(name, age, gender) {
  this.name = name;
  this.age = age;
  this.gender = gender;
}

Now let's say you've created some new persons:

var fred = new person("fred", 35, "male");
var mary = new person("mary", 24, "female");
var joe = new person("joe", 46, "male");

person currently has three properties, name,age, gender.

Using prototype you can add a new property to the object AND to all previously instantiated objects.

person.prototype.hairColor = null; <-- If you set this to "brown" all previously instantiated objects will have the value "brown". So fred.hairColor would be brown.

The great thing about this is that you can set all previously instantiated and future objects a default value without having to manually set the property on all of those objects.

The Muffin Man
  • 19,585
  • 30
  • 119
  • 191