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

// 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?
// index.html file

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

  <button id="button">Roll Dice</button>
  <script src="dice_constructor_function.js"></script>
  <script src="ui.js"></script>

1 Answer

Bibek Shakya
Bibek Shakya
12,790 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>