'this' in JavaScript

'this' in JavaScript

ยท

2 min read

Let's talk about something which is probably one of the most discussed topics of JavaScript - this ๐Ÿš€

this is a keyword in JavaScript which points to the calling object (the object that a method belongs to) and it is used to access the properties of that calling object.

const football= {
  player: "Messi",
  playsFor() {
    console.log("PSG");
  },
  goat() {
    console.log(player);
  }
};

football.playsFor();  //PSG
football.goat();  //ReferenceError: player is not defined

In the above example, football.goat() throws a ReferenceError even though player is a property of the football object. This happens because in the scope of the goat() method we don't automatically get access to other properties of the football object.

goat() {
  console.log(this.player); //Messi
}

Now, this will give us the correct output and will log Messi to the console. This is because when we use the this keyword, it references the calling object, i.e., the football object, which provides access to its properties.

Arrow Functions

In the above example we saw how this works with regular functions, now let's see how it works differently while using arrow functions.

goat : () => {
  console.log(this.player);  //undefined
}

Here we have used this and still it logs undefined which we were not expecting. ๐Ÿ˜ต Arrow functions inherently bind an already defined this value to the function itself that is NOT calling the object.

In this example, the value of this is the global object which does not have the player property and hence it returns undefined.

Arrow functions are usually avoided when using this inside a method.

That's it folks..

Thanks for reading, hope you liked the blog. I have just started out with writing blogs. I know blog writing is an art in itself. As this is my first ever blog do let me know about any advice/suggestions in the comments.

See you soon!

ย