Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript (2015) Constructor Functions and Prototypes Methods with Prototypes

Abe Layee
Abe Layee
8,378 Points

Prototype

Is a prototype a way to organize your code in JavaScript or a special function? I am confused here with prototype since is my first time learning about it.

2 Answers

A prototype is a property that all functions have by default. You can add methods to an object that will be available to all instances of that object.

One way I think of it is say you had 3 people living in your house and you all had chores on a list. You wouldn't make 3 copies of that list. Instead you'd make 1 copy and let everybody know where that copy was.

function User (name, id) {
  this.name = name;
  this.id = id;
}
User.prototype.showName = function () {
  console.log(this.name);
}
// Now you can create as many User instances as you want and instead of each one carrying a copy of the showName() function, 
//they are simply pointed to the showName() for instructions on what to do.
var treeHouseUser = new User ('Jane',2319);

treeHouseUser.showName();
Anthony c
Anthony c
20,907 Points

"One way I think of it is say you had 3 people living in your house and you all had chores on a list. You wouldn't make 3 copies of that list. Instead you'd make 1 copy and let everybody know where that copy was."

Best metaphor I've com across

Up there with using an automobile as an example of an object (with it's properties and methods).

Jeremy Barbe
Jeremy Barbe
8,728 Points

You just explained it a thousand times better than the video did. I was so confused. Less is more!

daviem
daviem
21,118 Points

Really well put Chris, cheers man, probably the clearest explanation I've seen yet