Generally, this keyword in JavaScript is confusing in some situations comparing to other programming languages like Java. Here, I will discuss some usages of this keyword and how it behaves in certain situations.
"this" keyword
Basically, this keyword in JavaScript is referring to the object that is executing the current function, also the parent object in some cases.
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
Then, we are going to figure out how this keyword behaves inside methods. Since the functions in JavaScript objects called as methods. If we invoke the print method it will be referred to the person object. That's because print is a method that attached to the person object. If we attach another method later to the object, it behaves like the same as below.
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.
Top comments (2)
Useful and informative
Thank you..