Whenever ‘this’ keyword is used in the global context i.e. not as a member of function or object declaration, it always refers to the Global object. The following example will illustrate this behavior.
If a function has a ‘this’ reference inside it, it can be said that the this refers to an object, not the function itself( which is generally the most common mistake programmers make ).
To determine which object the ‘this’ points to depends on how the function was called in the first place. The following example will put some light on the case.
Global myObj1 myObj2 undefined
Seeing the above example, we can see four different ways we can determine what this points to. There are four rules for how this gets set, let us explain these four for ourselves.
- myObj1.myFunc() sets this to the myObj1 object, here myObj1 is the owner of the Function myFunc and we are calling the function with the reference of the object itself, Thus in such cases this will refer to the owner object.
- myFunc.call(myObj2) sets this to the myObj2 object. This proves that this doesn’t always point to the owner object, it rather points to the object under whose scope the function was called.
- new myFunc() sets this to a brand new empty object thus we get undefined in the console log.
Note: We can determine whom ‘this’ refers by following this simple technique. Whenever a function containing ‘this’ is called, we should look at the immediate left of the parentheses pair “()”. If on the left side of the parentheses there is a reference, then “this” refers to the object it belongs to, otherwise, it refers to the global object. Provided we haven’t used any special Function to invoke the Function.
Inside an Event Handler
‘this’ inside of an event handler always refers to the element it was triggered on. Let us see an example to illustrate the same.
undefined Welcome to GFG!
We can see here that the first call was made in the Global scope thus ‘this’ referred to the Global Object and undefined was logged. Then we have copied the function to myElem.onclick event thus whenever the onclick function is invoked, ‘this’ refers to the myElem element which is the div with id clickMe thus “Welcome to GFG!” gets logged.
Now we can say that we know how this gets set to a particular object and we have one less misconception to worry about.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.