The Wayback Machine - https://web.archive.org/web/20240712073425/https://www.geeksforgeeks.org/javascript-this-identifier/
Open In App

JavaScript this Identifier

Last Updated : 09 Dec, 2022
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.



Similar Reads

JavaScript SyntaxError "variable" is a reserved identifier
This JavaScript exception variable is a reserved identifier occurs if the reserved keywords are used as identifiers. Message: SyntaxError: The use of a future reserved word for an identifier is invalid (Edge) SyntaxError: "x" is a reserved identifier (Firefox) SyntaxError: Unexpected reserved word (Chrome) Error Type: SyntaxError What happened? Whe
1 min read
JavaScript SyntaxError - Identifier starts immediately after numeric literal
This JavaScript exception identifier starts immediately after a numeric literal occurs if an identifier starts with a number. Message: SyntaxError: Unexpected identifier after numeric literal (Edge) SyntaxError: identifier starts immediately after numeric literal (Firefox) SyntaxError: Unexpected number (Chrome) Error Type: SyntaxError Cause of Err
1 min read
How to Resolve Identifier has Already been Declared Error in JavaScript ?
In JavaScript, the "Identifier has already been declared" error occurs when attempting to declare a variable or function with a name that has already been used within the same scope. In this article, we will explore this error in-depth with the potential reasons of occurrence, and solutions to resolve this error. What is the "Identifier has already
3 min read
JavaScript SyntaxError – Unexpected identifier
An “Unexpected identifier” error occurs when you have put an identifier where it is not supposed to be in your JavaScript code, it results in a syntax error that makes the interpreter fail to read the code, mostly, it happens because of incorrect identification or location in relation to expressions, variables and other structures found within the
3 min read
How to get the fragment identifier from a URL ?
A fragment identifier is a string of characters that refers to a resource that is inferior to a primary resource. Approach 1: We are able to print the fragment identifier by defining a new variable as location. hash and then display it with the help of document.getElementbyId() method. Syntax: var x = location.hash; document.getElementById("demo").
1 min read
JavaScript Course Understanding Code Structure in JavaScript
Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are &lt;script&gt; and &lt;/script&gt;. The code surrounded by the &lt;script&gt; and &lt;/script&gt; tags is called a script blog. The 'type' attribute was the most important attribute of &lt;script&gt; tag. However, it is no
4 min read
Introduction to JavaScript Course - Learn how to build a task tracker using JavaScript
This is an introductory course about JavaScript that will help you learn about the basics of javascript, to begin with, the dynamic part of web development. You will learn the basics like understanding code structures, loops, objects, etc. What this course is about? In this course we will teach you about the basics of the scripting language i.e) Ja
4 min read
JavaScript Course Loops in JavaScript
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. Example: In this example we will print the same things, again and again, to understand the work of Loops. &lt;script&gt; cons
4 min read
JavaScript Course Logical Operators in JavaScript
logical operator is mostly used to make decisions based on conditions specified for the statements. It can also be used to manipulate a boolean or set termination conditions for loops. There are three types of logical operators in Javascript: !(NOT): Converts operator to boolean and returns flipped value &amp;&amp;:(AND) Evaluates operands and retu
3 min read
JavaScript Course What is JavaScript ?
JavaScript is a very famous programming language that was originally started in the year of 1995 with the motive of making web pages alive. It is also an essential part of the web developer skillset. In simple terms, if you want to learn web development then learn HTML & CSS before starting JavaScript. HTML: HTML is used to create the structure of
3 min read
three90RightbarBannerImg