this Keyword JavaScript

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

Overview

You might have heard or used this keyword in various programming languages, this keyword in Javascript behaves a little differently. In JavaScript, the this keyword is a reference variable to the current object. Basically, it refers to the object which is defining the current context. In simple words, it points to the object which is executing the current piece of JavaScript Code this keyword in JavaScript can be used in global and function contexts. this takes different values in various scenarios. Let us dive in and learn more!

What is This Keyword?

While programming you might come across several scenarios where a single keyword can take different meanings. For example, the same keyword in different programming languages may have a little different meaning. Thus, it entirely depends on the context.

Similar to the above situation this keyword in JavaScript, as a reference variable points to an object, according to the context it was defined. What can be the possible contexts? How on the basis of these contexts, the object to which this refers is figured out? Let us explore more and learn about it!

Global Context

Global execution context basically means everything out of any function, in other words, the global scope. In Global Context, this refers to the global object for example in a browser, it is the window object or global object on Node.js.

Output:

True is returned since this refers to the window object.

If any property is assigned to this object in the global context, JavaScript will add it to the window object. This is because the global object and window object both imply the same as discussed above.

Output:

In the above case, window.name returns the value assigned to this.name.

Let us take an example to understand better:

Output:

In the above example, the function "Employe()" is being called in the global scope i.e. in the context of the window object. Hence, this can be alternatively called as window.Employee(). Thus, the this keyword in the function shall refer to the window object as well. Hence this.name returns James. Whereas, for the local scope if the variable is called i.e without this, it refers to the local name variable.

Function Context

In JavaScript, functions have their own properties. this is one of those properties. Hence, when this is used inside the function, its value will change according to the way the function is defined and invoked as the context also changes accordingly. Basically, invocation means the execution of the code inside the function or calling the functions. This can be done in the following ways:

Direct Invocation

It is a simple invocation method where we invoke a function using its name or some expressions that evaluate the function object. Here, this refers to the global object. Let us take an example:

Output:

So, the student() function is invoked through the simple function invocation and hence this refers to the global or window object.

Indirect Invocation

In JavaScript, all the functions are instances of the Function type. So basically, Function has two methods that can be used to set the reference of thethis keyword. These are:

  • call(): Calls a method using the owner object as a parameter.
  • apply(): Similar to call(), with apply() you can write a method that can be used on different objects.

When invoked using these methods, it is known as indirect invocation. We shall discuss these methods along with examples in a section ahead

Invoking Function: call() and apply()

call() and apply() essentially perform the same task. These methods are called on the function and take different parameters. These help you call or invoke the function indirectly and set the values of the this keyword.

Syntax for call()

Parameters for call():

  • thisArg: It is the object that this refers to inside the function. It is a compulsory parameter.
  • arguments: These are the function arguments. It is optional in nature.

Syntax for apply()

Parameters for apply():

  • thisArg: It is the object that this refers to inside the function. It is a compulsory parameter.
  • arrayOfarguments: apply() method takes arguments in form of an array. It is optional in nature.

Difference between call() and apply():

call()apply()
It takes comma-separated arguments.It takes an array of arguments.
It is faster as the arguments are already formattedIt is slower.

Let us take an example to understand better!

Output:

In the above program, we have called the getDetails() function indirectly using the call() and apply() methods. We have passed the student1 and student2 objects as the first argument of the call() and apply() methods, therefore, the corresponding Grade is obtained in each call. So this refers to the object passed as a parameter in each call. This is how we can set the value of this by indirectly invoking the function.

Bind()

call() and apply() can invoke a function but to return a new function that can be stored or passed bind() method is used. bind() was introduced in ECMAScript 5. When a function is invoked, this method sets the reference of this as per the provided value and returns a new function.

Syntax:

The bind method is called on the method as follows:

Parameters:

  • thisArg: Object that this shall refer to.
  • arg1, arg2, argN...: These are the function arguments, n in number.

Output:

In the above example, we have two objects student1 and student2. student1 has a method getName and the this inside this method shall refer to the student1 object itself. This is because in JavaScript this keyword inside the object's method refers to the owner object. Now in order to set the reference of this inside the method of student1 to another object, (student2 in this case), we have used the bind() method. As a parameter to the bind() method, student2 is passed. Thus, the reference of this is set according to the specified value.

Types of Binding in JavaScript

In a section before, we talked about how the reference value of this keyword in JavaScript depends on the way the function is invoked. Let us look at how the binding of this changes according to the way a function is called.

1. Default Binding

This is another name for the direct invocation, that we discussed above. this in default binding points to the global object. It is applied for standalone functions, it also acts as a fallback option for all the other types. In all the plain function calls, default binding applies. In short, the global object will bind to the called function.

Output

Explanation So as you see here, this defined inside standalone functions has pointed to the global objects.

2. Implicit Binding

While programming in JavaScript, you might have used dot notation to call a function of an object, this is also termed as. In such scenarios, the implicit binding applies. In such cases, this points to the object using which the function is invoked. Basically, the object written on the left side of the dot.

Output:

3. Explicit Binding

Explicit binding is another name for indirect invocation. This is applied with the help of the call() and apply() functions. Here, we force a function to use a particular object as its context. These methods along with examples have also been discussed in the previous sections.

4. Constructor Call or New Binding

This is applied with the help of the new() keyword. Here, when a constructor call is made or in simple words, a function is invoked with the help of the new() keyword, a new object is created. This object is further linked to the function that constructed it. Hence, this inside is linked to the newly created object.

Output

So as you can see here, a new object is created with the getValue function and this inside the function binds to this newly created object.

Use Case of This with Arrow Functions

Arrow functions were introduced in ES6. It is another way of writing a function expression in a shorter syntax. For example:

The above function can be reduced using the arrow function as:

So as you can see using the arrow notation we have simplified the syntax. The basic syntax of arrow notation is:

Here arg1, arg2.. are the arguments passed to the original function Arrow functions don't bind their own this or don't create their own execution context instead inherit this from the parent function where it is defined. This is also known as lexical scoping.

Output:

In the above program, childFunc, the inner arrow function inherits this from the outer function and follows its scope.

Class Context

The This keyword has a similar behavior in both classes and functions. Since in JavaScript functions and classes are also kind of similar with some differences. Inside a class constructor, this acts as a regular object. The non-static methods, inside the class, get added to the prototype of this keyword. Prototype is nothing but a working object instance. Let us look at an example to understand better.

Output:

So as you can see, like functions this is behaving in a similar manner here. For the static methods, class is added to the prototype of this. This isn't true in the case of non-static methods.

Derived Classes

Unlike the case of base class constructors as discussed above, derived constructors do not have any initial this binding. Calling super() keyword (used to access and call functions on the object's parent) will create a this binding inside the constructor.

Derived classes should not return before calling super() unless they are returning some Object or have no constructor. Either, reference error shall be thrown. As you can see in the example below:

This as an Object Method

If a function is called as an object's method, then this refers to the object the method is called on.

Output:

So as you can see here, getName() is called on the student object, hence this inside refers to the student object.

This on The Object's Prototype Chain

Every object has some private property that holds a link to another object known as its prototype. Further, This prototype object has its own prototype, and it goes on until an object is reached whose prototype is null. This is called the object prototype chain. The following image shall help you understand.

this-on-object-prototype-chain-example

If a method is defined on the object's prototype chain, in that case, this refers to the object on which the method was called.

Output:

Explanation In the above program, the object being assigned to variable y does not have the getValue property, thus it inherits the property from its prototype. So as getValue is being called as a method of object y, its this refers to y. Hence, verifies the concept of prototype chaining.

This With a Getter or Setter

Getters and Setters are used to read or update the property of an object. If a method is used as a getter or setter, then its this refers to the object from which the property is gotten or set.

Output:

Here, this inside the getter refers to the object values, as the property is gotten from it.

This as a Constructor

If a function is used for a constructor call with the help of the new() keyword, then the this keyword inside refers to the newly constructed object.

Output:

In the above program, for the function C2, since an object is returned during the construction, the newly created object that this was bound to, is getting discarded. thus, this.value1 can be easily eliminated since it does not affect the other piece of code.

This as a DOM Event Handler

Event handlers in JavaScript are used to handle user actions, verify user inputs, etc. If a function is being used as an event handler, then this refers to the element on which the event listener is placed.

In the above program, this is referring to the element on which the event listener is placed.

Precedence of This Keyword Bindings

To find which object this keyword in JavaScript refers to it follows the below-mentioned four rules in order. These are-

  1. new(): Firstly, it checks if the function is called with the new() keyword. If yes, this refers to the newly constructed object.
  2. call() and apply(): If the function is called with call() and apply(), the explicit binding applies.
  3. implicit binding: If the function is called within the context or with the context object, then implicit binding applies.
  4. default global scope: If none of the rules apply, the default rule applies which is this refers to the global object.

precedence-of-this-keyword-bindings

Supported Browsers

The list of browsers that support this keyword in JavaScript includes:

  • Google Chrome
  • Firefox
  • Safari
  • Microsoft Edge
  • Opera

Conclusion

  • this keyword in JavaScript is a reference variable and refers to the current or the object executing the JavaScript code.
  • It can be defined in global and function contexts.
  • In order to determine which object this keyword in JavaScript is referring to, this follows four rules:
    • new()
    • call() and apply()
    • implicit binding()
    • default global object
  • this keyword in JavaScript, takes different values in different contexts. There are 4 kinds of bindings, namely: default binding, implicit binding, explicit binding, and constructor call binding.