Understanding the (this)Keyword in JavaScript

Diwakar Verma - Oct 23 - - Dev Community

When you dive into JavaScript, one of the more confusing aspects can be the this keyword. However, once you understand how it works, it becomes a powerful tool in your programming arsenal. Let's break it down.
Think of this as a special word in JavaScript that points to a certain object, but what it points to depends on how and where you are using it. It changes based on the situation. So, let's break it down in simple terms:

When you’re not inside anything (global space): this points to the main environment (in the browser, that's the window).
When used inside an object’s method (a function attached to an object): this refers to that object.
In regular functions: If you're inside a function and using this, it points to the global object (unless you're in strict mode where it’s undefined).
In arrow functions: Unlike normal functions, this doesn’t point to anything new but sticks to whatever this was in the place where the arrow function was written.
In event listeners: If you add an event listener (like when a button is clicked), this points to the element that triggered the event (e.g., the button).
With methods like call, apply, or bind: You can change what this points to by manually setting it.

Now let me just give you a breif discription of call , apply or bind.
call(): Calls the function and sets this right away, with arguments passed individually.
apply(): Same as call(), but takes arguments as an array.
bind(): Doesn't call the function right away but returns a new function with this permanently set.
Image description**
Image description**

. . . . . . . . . . . . . . . .