Photo by Christin Hume on Unsplash
๐ฅ Cracking the 'this' Code in JavaScript
๐คก A Fun Guide to Understanding It
In JavaScript, when we mention this
, we're talking about what's happening at the moment. The value of this
is a bit like a shape-shifter, and it changes based on how you call a function or use an object.
So, here are the main rules that rule the game for this
in JavaScript! ๐ฎ
Global Context
When you're hanging out in the global zone (not inside any function), this
points to the big boss global object. In a browser, it's like saying, "Hey, meet the window object, my default buddy." ๐
console.log(this); // refers to the global object (e.g., window in a browser)
Click here to play with this code on codepen.
Function Context
So, if you're inside a function that's not playing sidekick to any object, guess what? this
is still pointing at the big boss global object. It's like saying, "Hey, global object, you're my go-to even when I'm not in an object method!" ๐
function exampleFunction() {
console.log(this);
}
exampleFunction(); // refers to the global object
Click here to play with this code on codepen.
Method Context
When you're cruising inside an object's method, check it out: this
is all about pointing at the object that threw the party. It's like saying, "Yo, I'm part of this object crew!" ๐๐จ
const obj = {
exampleMethod: function() {
console.log(this);
}
};
obj.exampleMethod(); // refers to the 'obj' object
Click here to play with this code on codepen.
Constructor Context
So, if you're throwing a party with a constructor function (you know, using that new keyword vibe), this
is like, "Hey there, brand new instance! I'm all yours!" ๐๐
function ExampleConstructor() {
console.log(this);
}
const exampleInstance = new ExampleConstructor(); // refers to the newly created instance
Click here to play with this code on codepen.
Event Handler Context
Imagine you're the cool DJ at a party, and this
in an event handler? It's like pointing at the star of the showโthe element that kicked off the party vibes! ๐ถ๐บ
<button onclick="console.log(this)">Click me</button>
Click here to play with this code on codepen.
Arrow Functions
Okay, so arrow functions? They're like chill buddies who don't have their own this
drama. Instead, they just borrow it from their cool surroundings, like a lexical context. It's all about sharing the good vibes! ๐ ๐
const arrowFunction = () => {
console.log(this); // 'this' is inherited from the surrounding context
};
arrowFunction();
Click here to play with this code on codepen.
Final thoughts
Wrapping your head around where a function struts its stuff is key for nailing down what this
is up to in JavaScript. This this
business can be a bit tricky, causing some head-scratching moments, so just keep your radar on high alert for the context it's rolling in! ๐ต๏ธโโ๏ธ๐ค
References
If you want to dive deep on this
keyword on javascript, I highly recommend checking out the following post: