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 trialErik Nuber
20,629 PointsUnderstanding Prototypes in javascript
I have been trying to figure this video out. I have watched it several times and have found it extremely confusing. So, I have looked online for help and, would like to know if this is what is actually happening...
function Dice(sides) {
this.sides = sides;
}
Dice.prototype.roll = function () {
var randomNumber = Math.floor(Math.random() * this.sides) + 1;
return randomNumber;
var dice = new Dice(6);
var dice10 = new Dice(10);
}
From what I can gather, though this looks confusing, what we are actually doing here is simply adding a new variable into the function Dice. Meaning, there is a function called Dice with a single variable of sides. By having a prototype, we are actually saying the function dice now contains a second variable called roll.
So, we could do something similar like...
Dice.prototype.material = "plastic";
and we are making another variable in the Dice function to describe the material of the die.
Is this correct or am I still misunderstanding?
4 Answers
jason chan
31,009 Pointsprototype is inheritance. Basically a new instance will inherit everything from the parent.
This video below helped me understand prototype. https://youtu.be/pu08qQCmw8I
jsdevtom
16,963 PointsI found the w3schools.com 's explanation the best. Their compact sentences made understanding easy: http://www.w3schools.com/js/js_object_prototypes.asp
Erik Nuber
20,629 PointsWanted to add one more link to this. After watching the youtube video, I followed the link to his other lessons and watched the three on Object Oriented Programming. If you are reading this question and, find yourself lost, I would definitely recommend watching the three videos, the one above and two others that do a great job explaining the material.
https://www.developphp.com/video/JavaScript/Class-OOP-Tutorial-Intro-to-Object-Oriented-Programming
Erik Nuber
20,629 PointsThank you, that was a good quick tutorial that made things easier to understand.
jason chan
31,009 PointsNo problem man. Glad I could help. ;)
Lincoln Wisely
7,481 PointsLincoln Wisely
7,481 PointsSuper helpful video – thanks for sharing.