Behavior inside global scope
First, we are going to consider the behavior of “this” in the global scope. In the global scope, this keyword is referring to the window object itself. The window object represents the document page that is currently opened in the browser window.
Behavior inside methods
If we are going to iterate through an array using a callback function, inside that callback function, this keyword is referring to the window object. because that function not a method of the person object, it is bind to the window object because that is a regular function and not a method.
Behavior inside regular functions
In regular functions, this keyword is referring to the window object unless it is a constructor function. Here, these functions will be created as functions of the window object.
In constructor functions, this keyword is referring to the created object of that class. When creating an object of a Person “this” will be pointed to that empty object. then we can assign properties to the object using this keyword.
Behavior inside arrow functions
In arrow functions, “this” will always refer to the parent of the object that defined the arrow function. Here, this keyword inside the arrow function is referring the person object.
Behavior inside event listeners
This can be used in DOM as well. In event listeners, this keyword is referring to the element that the event happened.
However, we can figure out what is “this” by keeping eye on what is on the left side when the function that contains this keyword invoking. That means on what object that function will be invoked. Then that object will be the object this keyword is referring to, like if we are invoking “this” directly in global scope there is nothing on the left side that means “this” will be referring to the window object or If we are invoking the method which contains “this”, then this keyword refers to the object that method is attached.