The “this” keyword in JavaScript can sometimes be a source of confusion for developers. It’s essential to understand what this refers to because it can change depending on the context.
Let’s use some Star Wars characters to explain the concept — I know you are thinking: “c’mon! another article using Star Wars characters!”.
Yes! 🤓 I am a Star Wars fan! 😁
However, imagine you have a Jedi named Luke Skywalker and a Sith Lord called Darth Vader. Both can use the Force, but how they use it is different.
In JavaScript, the this keyword is like the Force — it gives you the power to access object properties and methods, but how it’s used can vary.
Example:
const luke = {
name: 'Luke Skywalker',
useTheForce() {
console.log(`${this.name} uses the Force!`);
}
};
const vader = {
name: 'Darth Vader',
useTheForce() {
console.log(`${this.name} uses the Force!`);
}
};
luke.useTheForce(); // "Luke Skywalker uses the Force!"
vader.useTheForce(); // "Darth Vader uses the Force!"
In this code, luke and vader are objects with a useTheForce
method. When we call luke.useTheForce()
, the this keyword inside the method refers to luke, and when we call vader.useTheForce()
, this refers to vader.
So far, so good. 😑
It’s important to keep in mind that this can change depending on the context. For example, if we use useTheForce
as a regular function instead of a method, this will refer to the global object:
const useTheForce = luke.useTheForce;
useTheForce(); // "undefined uses the Force!"
In this case, this no longer refers to luke or vader, but to the global object, therefore the this.name
is undefined
.
The same will also happen when using the arrow function:
const obj = {
name: "Luke Skywalker",
printName: function() {
console.log(this.name);
},
printNameArrow: () => {
console.log(this.name);
}
};
obj.printName(); // outputs "Luke Skywalker"
obj.printNameArrow(); // outputs "undefined"
In the example above, the traditional function printName correctly outputs the name property of obj. However, the arrow function printNameArrow outputs undefined because it refers to the global this object, which does not have a name property.
In traditional functions, this is dynamically scoped, meaning it refers to the object that calls the function. However, in arrow functions, this is lexically scoped, meaning it refers to the object in the surrounding scope.
Overall, the this keyword is a powerful tool in JavaScript, but it’s also one that requires careful consideration.
With a little bit of practice, you’ll be able to use the Force — er, this — with confidence!
Happy coding! ✌️
Top comments (0)