What is this in JavaScript
Understanding 'this' in JavaScript
For someone who is beginning their journey in JavaScript, you may have come across the keyword 'this'. It is a unique concept in JavaScript that often confuses many learners. This blog post will take a gentle approach to explain the 'this' keyword. We'll go through code examples and use intuitive analogies to make it easier for you to understand. Let's dive in!
What is 'this'?
In JavaScript, 'this' is a special keyword that is automatically defined in every scope, which can be a function or a method. It refers to an object, and that object is usually the one currently being "used" or "worked on" by the code. It’s like when you are in a group of people and you say, “I am going to the store.” Everyone knows that by “I”, you mean yourself. In JavaScript, 'this' keyword is like the 'I' in the previous sentence, but for objects.
How Does 'this' Work?
Imagine you are at a self-service restaurant with a salad bar. You pick up a plate (this would be 'this' in JavaScript) and start putting food items on it. The plate represents the object that is currently being worked on, and the food items represent the properties of the object.
let plate = {
vegetables: 'carrots',
protein: 'chicken',
carb: 'rice',
describe: function() {
return `This plate has ${this.vegetables}, ${this.protein}, and ${this.carb}.`;
}
};
console.log(plate.describe());
In the above example, 'this' inside the 'describe' method refers to the 'plate' object.
'this' in a Function
When 'this' is used in a function, it usually refers to the global object, which is 'window' in a browser environment. It's like the salad bar analogy we used earlier, but instead of putting food on a specific plate, you're placing it on the main counter where everyone can access it.
function announceDish() {
this.dish = 'pasta';
}
announceDish();
console.log(window.dish); // Outputs: pasta
In the code example above, 'this' refers to the global 'window' object.
'this' in an Event Handler
When 'this' is used inside an event handler function, it refers to the HTML element that received the event. It's as if you were at a party and someone tapped your shoulder - 'this' would be you, the one who received the tap.
let button = document.querySelector('button');
button.addEventListener('click', function() {
this.style.backgroundColor = 'red';
});
In this example, 'this' inside the event handler function refers to the 'button' element.
'this' in a Constructor Function
A constructor function is a special type of function used to create objects of the same type. When 'this' is used in a constructor function, it refers to the newly created object. It's like a factory production line, where each new product (object) has the same properties but may have different values.
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
let myCar = new Car('Toyota', 'Corolla', 2007);
console.log(myCar.make); // Outputs: Toyota
In the above example, 'this' inside the 'Car' constructor function refers to the new object being created.
Conclusion
Understanding 'this' in JavaScript can be similar to learning how to drive. At first, the controls seem confusing and it's easy to forget when to use the clutch or the brake. But with time and practice, using 'this' becomes as easy as driving your favourite car. It's a powerful tool that can make your JavaScript code more efficient and flexible. So, keep practicing, keep experimenting, and soon you'll be driving through your JavaScript journey with ease.