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) Introduction to Methods Returning Values

Dice JS

Hello world, I've downloaded the project files from this video, since I'm using my own text editor. I opened the dice.js (dice_finished folder) and I want to know full explanation of this code, can somebody help me with that, I do not understand the prototype method?

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);

1 Answer

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

the first line is the constructor of the Dice object. it takes a number of sides as an argument. the next line is the roll function that returns a random integer based on the number of sides, to simulate rolling the Die (Dice). the next line is the instantiation of two Dice objects, a normal 6 sided Die and a 10 sided Die. in the last line both Dice are 'rolled' and it looks like the rolls are compared and sent to the console.