Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Object-Oriented JavaScript (2015) Introduction to Methods Adding a Method to an Object

Greg Schudel
Greg Schudel
4,090 Points

Trying to build Constructor Dice game

I am trying to go above and beyond and build a dice game from the previous lessons in this bunch. Below is my code with each file name labeled above. Not sure if my files will show correctly since I used Sublime text to do this project on my own

// dice.js file
//used a constructor function to substitute the object literal instead.

function dice(sides){

  this.sides = sides;

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

  }

}

var dice6 = new dice(6);

dice6.roll();
// ui.js file

function printNumber(number) {
  var placeholder = document.getElementById("placeholder");
  placeholder.innerHTML = number;
}

var button = document.getElementById("button");



button.onclick = function() {

  var result = dice6.roll(); // I changed this here to reference my constructor object, keep on getting 'undefined' in the console. Not sure why, any ideas?
  printNumber(result);
};
// index.html file

<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_constructor_function.js"></script>
  <script src="ui.js"></script>
</body>
</html>

1 Answer

Bibek Shakya
Bibek Shakya
10,434 Points

Your script seems perfect to me and it works well. However, according to the file name you have mentioned in top of each file, you should call the script in html as:

<script src="dice.js"></script> instead of <script src="dice_constructor_function.js"></script>