When learning JavaScript you might have come across the this
keyword, you might have thought it wasn’t that important to know, but understanding how the this
keyword works will definitely make you a better JavaScript developer. So let's get started! 🚀
So let's start by explaining what the this
keyword means in JavaScript. The this
keyword refers to the object it belongs to, with the this
keyword we can get access to properties and methods from the object it belongs to. Here’s an example:
In the example above we’ve defined an object called person
with two properties (name
& age
) and a method called greet
which logs the content to the console.
See how we’re able to access the name
& age
properties on the person
object, this is possible because the this
keyword refers to the object it belongs to, so we can access pretty much any property or method on any particular object.
What if we use “this” outside the object?
If we were to use the this
keyword outside an object then the this
keyword would refer to the global object ([object Window]
). The window object represents the browser's window, this means all the global JavaScript objects, functions, and variables automatically become members of the window object.
The “this” in arrow functions?
As part of ES6, arrow functions were introduced as a new way of defining functions. Here’s an example of one:
Don’t worry if you don’t know anything about arrow functions yet, I’ll discuss more about them in a different blog. We know that the this
keyword refers to the object it belongs to, with arrow functions the this
keyword works quite differently. In arrow functions, they don’t have their own bindings to the this
keyword. Here’s an example of what happens when we try to use the this
keyword in arrow functions:
When we try to access the name
and age
properties we get undefined
instead, in this scenario, it’s better to use regular function expressions.
To learn more about the this
keyword I really recommend you check out the MDN Web Docs for further explanation. Learn more about “this”
As always thank you for reading! 😊