JavaScript this keyword

JavaScript this keyword

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

What is JavaScript this keyword?

The JavaScript this keyword refers to the current object. It has different values, depending upon where it is defined or used

  • In a method, this refers to the owner of the method.
  • Using Alone, this refers to the global object.
  • Inside a function, this refers to the global object.
  • Inside a function, with strict mode, this is undefined.
  • Inside an event, this refers to the element that received the event.
  • Inside the Methods like call(), and apply() can refer this to any object.

In the below example we have used this keyword to know which object is referred by this keyword.

Example:

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

Output:

What is JavaScript this keyword

JavaScript this keyword with global context

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:

<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 this keyword with global context

The call() and apply() method (Explicit function binding)

The call() and apply() methods are predefined JavaScript methods.

This we already have discussed in Deep dive into Function and function Expressions. Let’s summarize once again.

Call() method

Syntax: functionName.call(thisArg, arg1, arg2, …);

The call() method invoke a function by functionName with a specified this value and arguments. The first argument of the call() method thisArg is the value of this. It allows you to set the this value with any given object. The rest arguments of the call() method arg1, arg2,… are the arguments of the function.

When we call the function, the JavaScript engine invokes the call() method of that function object.

apply() method

The Function.apply() method allows you to call a function with given this value and arguments provided as an array.

Syntax: functionName.apply(thisArg, [args]);

The apply() method accepts two arguments:

  • The thisArg is the value provided to call to the function functionName.
  • The args argument is an array that specifies the arguments of the function fn. Since the ES5, the args argument can be an array-like object or array object.

Note: The apply() method is similar to the call() method except that it takes the arguments of the function as an array instead of the individual arguments.

The call() & apply() method both can be used to call a method with different object as an argument.

Example:
<html>
<head>
    <title>call() and apply method example</title>
</head>
<body>
    <script>
        var emp_address = {
            fullAddress: function () {
                return this.company + " " + this.city + " " + this.state;
            }
        }
        var address = {
            company: "JavaScript Tutorial by Shagufta",
            city: "Mumbai",
            state: "MH",
        }
        document.writeln("call method: " + emp_address.fullAddress.call(address));
        document.writeln("<br/>apply method: "+emp_address.fullAddress.apply(address));
    </script>
</body>
</html>

Output:

The call() and apply() method (Explicit function binding) in JavaScript

The Bind() method in JavaScript

The bind() method was introduced in ECMAScript 5. It creates a new function, when called it has this which is set to specific value.

Syntax: functionName.bind(thisArg[, arg1[, arg2[, …]]])

the bind() method returns a copy of the function functionName with the specific this value (thisArg) and arguments (arg1, arg2, …).

Unlike the call() and apply() methods, the bind() method doesn’t execute the function immediately. It only returns the function.

The bind() method allows an object to take a method from another object without making a copy of that method. This is called function borrowing in JavaScript.

Example:
<html>
<head>
    <title>bind() method example</title>
</head>
<body>
    <script>
        let running = {
            name: 'Running',
            run: function (speed) {
                document.write(this.name + ' runs at ' + speed + ' mph.');
            }
        };
        let flying = {
            name: 'Flying',
            fly: function (speed) {
                document.write(this.name + ' flies at ' + speed + ' mph.');
            }
        };
        let run = running.run.bind(flying, 20);
        run();
    </script>
</body>
</html>

Output:

The Bind() method in JavaScript

In the next article, I am going to discuss JavaScript let keyword in detail. Here, in this article, I try to explain JavaScript this keyword with examples. I hope this article will helps you with your need. 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.