๐ฅ Cracking the 'this' Code in JavaScript
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:
Subscribe to my newsletter
Read articles from Ricardo Rocha // ๐จโ๐ป directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Ricardo Rocha // ๐จโ๐ป
Ricardo Rocha // ๐จโ๐ป
Hey there ๐! ๐ So, here's the lowdown โ I'm a full-stack web dev with a serious crush on front-end development. Armed with a master's in Software Engineering, I've been rocking the programming scene for a solid decade. I've got this knack for software architecture, team and project management, and even dabble in the magical realm of deep learning (yeah, AI, baby!). My coding toolbox ๐งฐ is stacked โ JavaScript, TypeScript, React, Angular, C#, SQL, NoSQL - you name it. Nevertheless, learning is my best tool ๐! But here's the thing โ I'm not just about the code. My soft skills game is strong โ think big-picture pondering, critical thinking, and communication skills sharper than a ninja's blade. Leading, mentoring, and rocking successful projects? Yeah, that's my jam as well. Now, outside the coding dojo, I'm a music lover. Saxophone and piano are my instruments of choice, teaching me the art of teamwork and staying cool under pressure. I've got a soft spot for giving back too ๐ฅฐ. I've lent a hand to the Jacksonville Human Society (dog shelter). And speaking of sharing wisdom, I also write blogs and buzz around on Twitter, LinkedIn, Stackoverflow and my own Blog. Go ahead and check me out: Linkedin (https://www.linkedin.com/in/ricardogomesrocha/) Stackoverflow (https://stackoverflow.com/users/5148197/ricardo-rocha) Twitter (https://twitter.com/RochaDaRicardo) Github (https://github.com/RicardoGomesRocha) Blog (https://ricardo-tech-lover.hashnode.dev/) Let's connect and dive into the exciting world of web development! Cheers ๐ฅ, Ricardo ๐