Open In App

JavaScript this Identifier

Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, ‘this‘ identifier can be used in different contexts and scopes. Let us go through each to determine what this is and how it is decided.

Global Scope: Whenever ‘this’ keyword is used in the global context i.e. not as a member of a function or object declaration, it always refers to the Global object. The following example will illustrate this behavior.

Example:

javascript




<script>
    // Declaring variable in global context.
    var a = "GFG";
    console.log(a);
     
    // Using this we refer to the Global Context.
    // And update the value of a we declared previously.
    this.a = "GeeksforGeeks";
    console.log(a);
</script>


Output:

GFG
GeeksforGeeks

Functional Scope: If a function has a ‘this’ reference inside it, it can be said that 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.

Example:

javascript




<script>
    // Function that contains this.
    function myFunc() {
        console.log(this.a);
    }
 
    var a = "Global";
 
    // Owner of the function.
    var myObj1 = {
        a: "myObj1",
        myFunc: myFunc
    };
 
    // Object other than the owner.
    var myObj2 = {
        a: "myObj2"
    };
 
    // Call the function in Global Scope.
    myFunc();
 
    // Call the function from the reference of owner.
    myObj1.myFunc();
 
    // Call the function from the reference
    // of object other than the owner.
    myFunc.call(myObj2);
 
    // Create a new undefined object.
    new myFunc();
</script>


Output:

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.

  • In the first call, myFunc() ends up setting this to the Global object in non-strict mode. Whereas in strict mode this would be undefined and JavaScript will throw an error in accessing the property.
  • 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 to 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.

Example:

javascript




<button id="clickMe">Welcome to GFG!</button>
<script>
    function clickedMe() {
        console.log(this.innerHTML);
    }
       
    clickedMe(); // undefined because global object.
       
    var myElem = document.getElementById('clickMe');
    myElem.onclick = clickedMe;
        
    myElem.onclick(); // Welcome to GFG!
</script>


Output: 

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 copied the function to my Elem.onclick event thus whenever the onclick function is invoked, ‘this’ refers to my Elem 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.



Last Updated : 09 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads