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
Daniel Sokol
14,888 PointsProject file 'dice_finished' different than video
Hi there...
Is it me, or does the video have different code than the project files for the dice roll project?
The dice_finished project file shows the following:
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);
console.log(dice.roll === dice10.roll);
Specifically, I'm confused about 'Dice.prototype.roll' and also using the keyword 'new' in the variables which is not discussed in the videos.
Thanks!
1 Answer
Steven Parker
243,656 PointsThe "new" keyword constructs an object using the constructor function that follows it. It insures that references to "this" inside the constructor point to the object being created.
Using prototype to add new methods to a constructor function has two major benefits:
- the method becomes available to previously constructed instances of the object
- the method code is shared between the objects instead of each having its own copy
The sample code above appears to be designed to illustrate the second concept. The final line logs "true" to the console to show that both objects share the same method code.
sp
Steven Parker
243,656 PointsSteven Parker
243,656 PointsWhich course and video are you referring to? Can you provide a link?