JavaScript this Keyword

JavaScript this Keyword with Examples

In this article, I am going to discuss JavaScript this keyword with Examples. Please read our previous article where we discussed ES6 New Target Property. At the end of this article, you will understand what is JavaScript this keyword and when and how to use JavaScript this keyword with examples.

JavaScript this Keyword

JavaScript this keyword is one of the most difficult topics in JavaScript language. Even if a developer knows the concept behind this, it can still be challenging to work with in real scenario code. this keyword refers to the current object.

  1. It has different values, depending on where it is defined or used.
  2. In a method, this refers to the owner of the method.
  3. Using Alone, this refers to the global object.
  4. Inside a function, this refers to the global object.
  5. Inside a function, with strict mode, this is undefined.
  6. Inside an event, this refers to the element that received the event.
  7. Inside the Methods like call(), and apply() can refer this to any object.

Here we will learn more about this keyword with the help of different examples. In the below example, we have used the object literal method with this keyword. The following ways can be used to know which object is referred to by this keyword.

Example: JavaScript this keyword
<html>
<head>
    <title>JavaScript this keyword example</title>
</head>
<body>
    <script>
        var details =
        {
            company: "Dot Net Tutorials",
            city: "Mumbai",
            state: "MH",
            fullAddress: function () {
                return this.company + " " + this.city + " " + this.state;
            }
        };
        var fetch = details.fullAddress();
        document.writeln(fetch);
    </script>
</body>
</html>

Output: Dot Net Tutorials Mumbai MH

The example below creates an object and uses this keyword within it to refer to the object. This allows us to access object data and methods. In the below example, the constructor is used. The constructor’s main purpose is to initialize the object.

Example: JavaScript this keyword with class object
<html>
<head>
    <title>JavaScript this keyword with class object example</title>
</head>
<body>
    <script>
        class User {

            //Object constructor syntax
            constructor(name, age, bloodgroup) {
                this.name = name;
                this.age = age;
                this.bloodgroup = bloodgroup;
            }

            //method outside the class constructor, Get the age, name, and blood group
            bornYear() {
                return 2015 - this.age + ' birth of ' + this.name + ' with bloodgroup: ' + this.bloodgroup;
            }
        }

        const newUser = new User("John", 42, "A+");
        console.log(newUser.bornYear()); // 1973 birth of John with bloodgroup: A+
    </script>
</body>
</html>

Output: Press F12 and go to the Console section

JavaScript this keyword with class object

There are six rules to help us determine what the value of this will be:

  1. When you create an object using the new keyword with a constructor function/class, this will refer to the new object inside the function.
  2. Using bind, call, or apply will override the value inside a function, and you can hardcode its value for this.
  3. If a function is called on an object as a method, this will refer to the object that is calling it. For example, myObject.method() would have a value of this that refers to myObject.
  4. If a function is executed without any of the three previous criteria being applied, this will refer to the global object, which is a window in the browser or global in Node.
  5. If multiple rules from above apply, it will use the rule that comes first in this list.
  6. Arrow functions ignore all the above rules, and the value of this is determined by the scope enclosed by the arrow function.
JavaScript this keyword with global context / this Inside Global Scope

In the global context, a variable is declared outside the function. In other words, the Variable declared outside a function is belong to the global context and the value of this in the global context is the same as the global object. Here, this keyword refers to the window object.

Example: JavaScript this keyword with global context
<html>
<head>
    <title>this keyword with global context example</title>
</head>
<body>
    <script>
        var tutorialName = "JavaScript Tutorial";
        function data() {
            document.write(this.tutorialName);
        }
        data();
    </script>
</body>
</html>

Output: JavaScript Tutorial

The JavaScript global scope is the context within which everything it has is executed by default. It includes all variables, objects, and references that are not defined within a programmer’s customized scope. In JavaScript, global scope refers to the entire execution environment.

The window object is the global context in the browser. JavaScript leaves the global context undefined if it is not set in strict mode. When this is used alone, this refers to the global object that is the window object in the browsers.

Example: JavaScript this keyword inside global scope
<html>
<head>
    <title> JavaScript this keyword inside global scope example</title>
</head>
<body>
    <script>
        console.log(this === window) //true

        let x = this;
        console.log(x); //Window{}

        this.name = 'Angel';
        console.log(window.name) //Angel
    </script>
</body>
</html>

Output: Press F12 and go to the Console section

JavaScript this keyword inside global scope

Here, this.name is the same as window.name.

JavaScript this Keyword Inside Function

When this is used inside a function, this refers to the global object that is the window object in browsers.

Example: JavaScript this keyword inside the function
<html>
<head>
    <title> JavaScript this keyword inside function example</title>
</head>
<body>
    <script>
        function msg() {
            //this inside function
            //This refers to the global object
            console.log(this);
        }

        msg() //Window{}
    </script>
</body>
</html>

Output: Press F12 and go to the Console section

JavaScript this Keyword Inside Function

JavaScript this keyword Inside Constructor Function

In JavaScript, we have seen the constructor function. Technically, a constructor function is just a regular function used to create multiple similar objects with the following convention:

  1. The name of a constructor function starts with a capital letter like Person, Course, etc.
  2. A constructor function should be called only with the new operator.

The new operator does the following:

  • Create a new empty object and assign it to this variable.
  • Assign the arguments ‘John’ and ‘Maria’ to the age and name properties of the object.
  • Return this value.

When a function is used as a constructor function, this refers to the object within which it is used. What we discussed above is given in the below example.

Example: this keyword inside the Constructor function
<html>
<head>
    <title>JavaScript this keyword inside constructor function example</title>
</head>
<body>
    <script>
        //Using the constructor of the Function object.

        //Object constructor syntax
        function Person() {
            this.name = 'Angel';
            this.age = 15;
            this.bloodgroup = 'B+';

            console.log(this);
        }

        let john = new Person();
        console.log(john.name ,john.age ,john.bloodgroup );
    </script>
</body>
</html>

Output: Press F12 and go to the Console section

JavaScript this keyword Inside Constructor Function

JavaScript this keyword Inside Object Method

When this is used inside an Object’s method, this refers to the object it lies within.

Example: JavaScript this keyword inside an object method
<html>
<head>
    <title>JavaScript this keyword inside object method example</title>
</head>
<body>
    <script>
        //Object constructor syntax
        const person= {
            name: 'Angel',
            age : 15,
            bloodgroup : 'B+',

            //this refers to the Object itself
            greet(){
                console.log(this);
                console.log(this.name);
            }
        }

        person.greet();
    </script>
</body>
</html>

Output: Press F12 and go to the Console section

JavaScript this keyword Inside Object Method

JavaScript this keyword Inside Inner Function

When we access this inside an inner function or inside a method, this refers to the global object.

Example: this keyword inside the inner function
<html>
<head>
    <title>JavaScript this keyword inside inner function example</title>
</head>
<body>
    <script>
        //Object constructor syntax
        const person= {
            name: 'Angel',
            age : 15,
            bloodgroup : 'B+',

            //this refers to the Object itself
            greet(){
                console.log(this); // {name: 'Angel', age: 15, bloodgroup: ...}
                console.log(this.age); //15

                //inner function
                function innerFunc(){
                    //this refers to the global object
                    console.log(this); //Window {...}
                    console.log(this.age); //undefined
                }
                innerFunc();
            }
        }

        person.greet();
    </script>
</body>
</html>

Output: Press F12 and go to the Console section

JavaScript this keyword Inside Inner Function

JavaScript this keyword Inside Arrow Function

syntax: () => {…}

Inside the arrow function, this keyword refers to the parent scope.

Example: this keyword inside the inner arrow function
<html>
<head>
    <title>JavaScript this keyword inside Arrow function example</title>
</head>
<body>
    <script>
        const printMsg=()=>{
            console.log(this); 
        }
        printMsg() //Window{...}        
    </script>
</body>
</html>

Output: Press F12 and go to the Console section

JavaScript this keyword Inside Arrow Function

When we use this inside an arrow function, this refers to its parent scope object.

Example: JavaScript this keyword inside the inner arrow function, refers to its parent’s scope object
<html>
<head>
    <title>JavaScript this keyword inside Arrow function, refers to its parents scope object example</title>
</head>
<body>
    <script>
        //Object constructor syntax
        const person = { 
            name: 'Angel',
            age: 15,
            bloodgroup: 'B+',

            //method
            printMsg() {
                let hello = () => console.log(this.name);
                hello();
            }
        }

        person.printMsg();
    </script>
</body>
</html>

Output: Press F12 and go to the Console section

JavaScript this keyword inside the inner arrow function, refers to its parent’s scope object

Here, this.name inside the hello() method/ function refers to the person object. We can also use the arrow function to solve the issue of having undefined when using a function inside a method.

Example: this keyword inside the inner arrow function, using a function inside a method
<html>
<head>
    <title>JavaScript this keyword inside Arrow function, using a function inside a method example</title>
</head>
<body>
    <script>
        //Object constructor syntax
        const person = {
            name: 'Angel',
            age: 15,
            bloodgroup: 'B+',

            //this refers to the Object itself
            greet() {
                console.log(this); // {name: 'Angel', age: 15, bloodgroup: ...}
                console.log(this.age); //15

                //inner function
                let innerFunc = () => {
                    //this refers to the global object
                    console.log(this); // {name: 'Angel', age: 15, bloodgroup: ...}
                    console.log(this.age); //15
                }
                innerFunc();
            }
        }

        person.greet();
    </script>
</body>
</html>

Output: Press F12 and go to the Console section

JavaScript this keyword with Examples

Here, the innerFunc() method is defined using the arrow function. It takes this from its parent scope. Hence, this,age gives 15.

In the next article, I am going to discuss Explicit Function Binding in JavaScript with Examples. Here, in this article, I try to explain JavaScript this keyword with Examples. I hope you enjoy this JavaScript this keyword article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *