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 Challenge Solution

Yohanan Braun-Feder
Yohanan Braun-Feder
6,101 Points

I achieved the same result but longer code... the example given does not work.

hi, created this code to process the function on this challenge:

function Dice(sides) {
    this.sides = sides;
    this.roll = function () {
  var randomNumber = Math.floor(Math.random() * this.sides) + 1;
 return randomNumber;
}
}

var dice = new Dice(6);

//this is as far as the course code goes, however when i use this code i get a blank dice roll. I have to add this next part for the roll to actually display on the page:

function print(message) {
  var outputDiv = document.getElementById("placeholder");
  outputDiv.innerHTML = message;
}

print(dice.roll());

the html for this challenge:

<html>
<head>
    <title>Dice Simulator 2015</title>
    <link rel="stylesheet" href="style.css">
</head>  
<body>
  <p id="placeholder">

  </p>
  <button id="button">Roll Dice</button>
  <script src="dice.js"></script>
  <script src="ui.js"></script>
</body>
</html>

2 Answers

The ui.js file in this Workspace does not reflect the update to the var result for the button.onclick method. Change it to var result = dice.roll(); and the code given by Andrew will work.

Fabio Silva
Fabio Silva
5,097 Points

My solution was similar to Andrew's but I used the console.log function to display the result. However, it only worked with one instance. If I tried to log the random number of another instance it wouldn't work.

My code:

var Dice = function (sides){ this.sides = sides; this.roll = function () { var randomNumber = Math.floor(Math.random() * this.sides) + 1; return randomNumber; } }

var dice1 = new Dice(3); var dice2 = new Dice(6); dice1.roll(console.log(this.randomNumber)); dice2.roll(console.log(this.randomNumber));