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.
The JavaScript 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.
The window represents the browser window and this window is represented by a window object.
Here's what you'll get when you type window in your browser console.
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!
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 simpler terms, this points to whatever object that's on the left of the dot.
Here's what you see when use log this as a method in an object.
In this case, this.newProp actually returned newObject.newProp.
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?
Remember: bind()
Check this out for more information.
What does bind() do?
The bind() method creates a new function, when invoked, has the this set to your provided value.
The bind() method returns a copy of the function where this is set to the first argument passed into bind()
Here's what you see when you manually bind this to a provided value.
We pass in an argument as an object into the bind method with property of name : The Hacker Collective. this is now set to the first argument passed into bind().
We're saving it in a variable called bindExample because 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 name: The Hacker Collective object, rather than windows like we saw in example (1).
Email us directly at hello@sigmaschool.co!
Want to learn to find out more about what we do?
Learn more here: https://sigmaschool.co
Let’s get social! Find us on:
Facebook: https://www.facebook.com/joinsigma/
Instagram: https://www.instagram.com/joinsigma/
Linkedin: https://linkedin.com/company/79085028/