๐Ÿ’ฅ 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! ๐ŸŽฎ

๐Ÿ’ก
๐Ÿ’ก The examples make use of the browser console for an interactive experience. To view them on CodePen, follow the steps outlined in this handy tutorial: CodePen Console Tutorial.

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.

๐Ÿ’ก
Want to know more about lexical context? Check out this post.

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:

10
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 ๐Ÿ‘Š