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 Methods with Prototypes

見綸 陳
見綸 陳
6,333 Points

Return function value in prototype

I try to console.log dice.roll and dice10.roll, but the outcome doesn't return the value. Should it be return a number value?

I open the chrome dev tool. The console.log outcome is a function, as following

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

Here is my code!

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);
console.log(dice.roll);
console.log(dice10.roll);

1 Answer

You need to invoke your functions or else they are just returning an echo of your script. This is what I did:

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());  //<===== Notice the parentheses after each function
console.log(dice.roll());  //<===== Notice the parentheses after the function
console.log(dice10.roll());  //<===== Notice the parentheses after the function