The this statement – an elusive concept to grasp. So what does it do? When can you use it and why would you even want to?
Global Context – via MDN
console.log(this.document === document); // true
// In web browsers, the window object is also the global object:
console.log(this === window); // true
this.a = 37;
console.log(window.a); // 37
What is this?
What does this refer to?
this refers to data that’s passed into the parent of this. As an object-oriented keyword, this starts out as a child of the global window object.
How do I make it refer to what I want to refer it to?
this is already an available reference for functions, and should only be used for that.
Check to see what this refers to by using
If you’re wanting to use this inside of an inner function/closure (function within a function), this reference will be different than in the parent. One common way to pass this reference is to ‘bind’ this to the original reference
this.handleSearchTermChange = this.handleSearchTermChange.bind(this)
When should I use this?
Use this to help make changes to the original function’s object. Whatever has been pulled into the function is the object that will be edited.
Why would I want to use this, instead of directly writing what is being referred?
This is an extremely useful shortcut, that not only helps with code readability but also allows you to access an object with much greater ease than typing out the reference each time.
When should I not use this?
Don’t use this if you’re not sure what it refers to.
Most important things to know about this:
This is an extremely powerful keyword that an easier work environment to an object passed to a function
QuirksMode – http://www.quirksmode.org/js/this.html