Here's a little cheat sheet to help you understand the
this keyword to learn it for the first time and to also serve as a reference in the future when you come across "this" problem again.
By the end of this, you'll understand all the key things you need to know about
this keyword refers to the object it belongs to. This means it changes in different cases.
For me, I see it as a cool variable that changes depending on the situation. Let's take a look at what it means in different contexts.
1. The base scenario, in a normal function or if you're not in a function at all,
this points to
window represents the browser window and this window is represented by a window object.
To find out what "this" really is. Let's just log it to the console.
It's quite clear here we get the Window object!
2. In a constructor function,
this refers to the object that the constructor is creating.
Let's create a constructor function. The way you call a constructor is by calling it with a
new keyword infront, and then pass in whatever argument you want to give it. Let's take a look at an example.
Under the same
Community constructor function,
this referred to different objects (instances) that the constructor function created.
- In the
this.namereturned "The Hacker Collective".
- In the
this.namereturned "Another Community".
3. In a normal object,
this points to the object it belongs to.
In simpler terms,
this points to whatever object that's on the left of the dot.
In this case,
this.newProp actually returned
4. What if you want to deliberately set the value of
What's different about this compared to the previous 3 contexts? Here, you have all the control. You decide what
this is equal to.
Remember point (1)?
We get back
window when we logged
this in a normal function.
What if we wanted to control the value of
this and change it from
window (which is what it is now), to something different?
Check this out for more information.
bind() method creates a new function, when invoked, has the
this set to your provided value.
bind() method returns a copy of the function where
this is set to the first argument passed into
We pass in an argument as an object into the
bind method with property of
The Hacker Collective.
this is now set to the first argument passed into
We're saving it in a variable called
bind() does not run the function, it returns a copy of the function.
When we call the
bindExample() function, it prints out the property:value pair we deliberately defined, because
this is now the
The Hacker Collective object, rather than
windows like we saw in example (1).
Any new ideas? Want to contribute to the community to add value to junior developers?
Email us: email@example.com