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!
Can anyone come up with a good prototype example in JS that helps me understand what prototypes are?
Asked
Active
Viewed 116 times
-5
-
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Inheritance_and_the_prototype_chain – Denys Séguret Feb 08 '13 at 21:08
-
[How does JavaScript .prototype work?](http://stackoverflow.com/questions/572897/how-does-javascript-prototype-work) – kei Feb 08 '13 at 21:10
-
duplicate of http://stackoverflow.com/questions/2064731/good-example-of-javascripts-prototype-based-inheritance – Shanimal Feb 08 '13 at 21:11
-
Please see my answer. I've done my best to make it simple. – The Muffin Man Feb 08 '13 at 21:24
1 Answers
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