this
The this
keyword is one of the toughest things for newcomers to wrap their heads around. Let's take our time and just do a little bit for now.
File Location
Let's do a little more practice:
Grammar Refresher
Many people start learning about the this
keyword with a refresher on Pronouns and Antecedents in English. Let's take that approach and go way back to grade school. Consider the following sentence:
Remember that a pronoun
is a word that replaces a noun. In the example sentence, 'her' is our pronoun.
The antecedent
is the word that the pronoun refers back to. In this example sentence the antecedent would be 'Carolyn'.
this in coding
We have a similar concept in coding with the 'this' keyword. Let's look at a sample chunk of code:
So in the above code, here's what we've done: 1. We've created an Object Constructor Function that can create new instances of Player
. It can create new Player
objects.
2. We've created two instances of the objects and passed in values into the arguments. 3. We are console logging the name value of each of those separate objects.
this
this
But what about The this
keyword? Analyzing #1 a little bit more, consider these things: 1. There are two parameters name
and points
. 2. These values get passed to the RHS inside the function, as noted below:
this.name
will store those values on the lhs for each individual object.this.name
is working like a pronoun, and it's antecedent is the object that the particular instance refers to. That's confusing, so let's talk about that in concrete terms:When we print
console.log(quincy.name)
, thethis
keyword is referring to the Player instance calledquincy
.When we print
console.log(paul.name)
, thethis
keyword is referring to Player instanced called `paul.If we keep creating new instances of those objects,
this
we refer to the current object when it is called and the.
operator is used to access the specific property values for that object.
Key Takeaway
In general
this
refers to the current object, to the calling object.There are a lot more rules and nuances to deal with here, but this should be enough to get you started.
Practice
Write a constructor function called
Band
that takes in two parameters:name
andgenre
.Use what you've learned with the
this
to align the left hand side with the value of the right hand side.Use the constructor function to create two new objects.
Print the name and genre for both of those objects.
Last updated