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
Erwan EL
7,669 PointsWhy using .this into the roll method
function Dice (sides) {
this.sides = sides;
this.roll = () => {
return Math.floor(Math.random() * this.sides) + 1;
}
}
function Dice (sides) {
this.sides = sides;
this.roll = () => {
return Math.floor(Math.random() * sides) + 1;
}
}
Tried both with various dices and both works.
2 Answers
Steven Parker
243,318 PointsIn the first, you establish an instance variable named "sides" and use it in the "roll" method.
In the second, you establish but then ignore the instance variable. The "roll" method is using the argument that was passed in directly.
It might not seem different until you try to reconfigure the object:
var a = new Dice1(6); // this is the first version, just renamed to be unique
var b = new Dice2(6); // the second version
a.roll(); // this gives a number from 1-6
b.roll(); // this also gives a number from 1-6 - the same, so far
a.sides = 100; // now we reconfigure for 100 sides
b.sides = 100; // same here (it seems)
a.roll(); // now this gives a number from 1-100
b.roll(); // but this STILL gives a number from 1-6 !
Since you don't use the "this.sides", you could actually condense the second function to just this:
function Dice(sides) {
this.roll = () => Math.floor(Math.random() * sides) + 1;
}
Erwan EL
7,669 PointsThanks a lot, it's very clear now.