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 trialKenny Brijs
8,191 PointsQuestion about `this`
I was wondering about this
in the following piece of code and why it works:
function rollDice() {
return Math.floor(Math.random() * this.sides) + 1;
}
function Dice (sides) {
this.sides = sides;
this.roll = rollDice;
}
You said that this
references to βthe owner of the object,β so in this case:
The this
in rollDice()
should reference to this.roll
of Dice()
since this.roll = rollDice;
and thus this.roll
is the owner of the rollDice
function here, no?
So this.sides
in rollDice()
should by trying to access this.roll.sides
from Dice()
, the way I see it.
I know I am mistaken because in rollDice()
the this.sides
is indeed referencing the this.sides
from Dice()
like we need it to, but I'm confused since to me this.roll
βand not the instance of Dice
β seems to be the owner of the rollDice
function.
I hope this makes sense (pun intended), it's quite a difficult subject to explain :)
2 Answers
Chyno Deluxe
16,936 PointsHello Kenny,
When working with Constructor functions, the this keyword will always reference the instance of a parent object or event, in this case, Dice().
The Dice() function creates an instance of rollDice() by giving it the property of this.roll. Therefore it inherits properties of the Dice() instance.
So essentially what this.roll is doing is the following.
function Dice (sides) {
this.sides = sides;
rollDice(this.sides);
}
but with the this.roll name it becomes a property of the Dice() instance.
jcorum
71,830 PointsThink of this as a pronoun. Sometimes it means me, and sometimes it's possessive: my
So in this code:
function Dice (sides) {
this.sides = sides;
this.roll = rollDice;
}
it means make my sides variable have the value passed in as the sides parameter. Etc.
When a Dice object is created, you pass it a number for the sides variable, and this.sides = sides takes that value and stores it as the value of the object's sides variable.
Andrew Chalkley
Treehouse Guest TeacherI like that explanation: "my".
Andrew Chalkley
Treehouse Guest TeacherAndrew Chalkley
Treehouse Guest TeacherThe dice instance (
this
) in the Dice constructor becomes the owner of therollDice
method. Thereforethis.sides
is referring to the dice instance's (this
)sides
.