This is Javascript
In this article, we are gonna talk about the this
keyword. What is this? How does this
work? and why this
is it not so hard?
this
is a keyword in Javascript and it refers to different data depending on how you use this
( this
is going to be funny 😅)
First of all, if you currently call this
in the global scope of your object (and if you don’t know what a global scope is: this), this
will refer you to the global object.
In case you console.log
the this
keyword in a JS code that’ll be executed in a browser, the global object will be Window.
Alright, this is good!
Now, if we console.log
this inside of a function… What will happen?
Same as with our global this
, a this
invoked inside of a function statement will refer to the global object.
But, what about functions declared as methods inside of an object?
First, bear in mind that in Javascript all objects inherit properties from other objects and functions are first-class objects, which basically means that functions are objects too (callable objects). So, when this
is called inside of an object method it is referring to the object itself. And at that point, our object only has one element: the getUserName()
method.
If we add more attributes to our user
object and call again our getUserName
method, this is what our console will print:
So, this
is still basically referring to our object. And now that we have more properties, let’s give getUserName
a more conscious meaning:
**Special Note: When executing JS code in strict mode. If you use
this
inside of a function, it’ll beundefined
.
this
inside of Event Handlers
For this example we have a button element:
If we assign a function to an event listener and call this
inside of that function, our chameleonic keyword will refer us to the element that is receiving the event, in this case, the HTMLButtonElement
:
Bear in mind that when using methods like bind()
, this
will refer to any object, which means that with Function.prototype.bind()
we can provide a new value to be set to the this
keyword… But there will be another occasion for getting our hands dirty with this
… or maybe that!
Conclusion
The this
keyword is very powerful if we do know how this
works! Remember that everything in Javascript is an object! so for understand which objects this
refers to, we should ask ourselves:
- Is
this
called from bind(), apply() or call(), or… - Is
this
called inside a function statement? - Is
this
called in a method? - Is
this
called globally?
Thanks and don’t forget to read about this
:
Thanks for reading this
! Cheers!