this keyword, you might have thought it wasn’t that important to know, but understanding how the
So let's start by explaining what 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 (
age) and a method called
greet which logs the content to the console.
See how we’re able to access the
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 (
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
age properties we get
undefined instead, in this scenario, it’s better to use regular function expressions.
As always thank you for reading! 😊