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

Question about `this`

Hi Andrew Chalkley

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

Andrew Chalkley
Andrew Chalkley
Treehouse Guest Teacher

The dice instance (this) in the Dice constructor becomes the owner of the rollDice method. Therefore this.sides is referring to the dice instance's (this) sides.

2 Answers

Hello 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.

Think 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.