What does “this” keyword mean in JavaScript ?

In JavaScript, the ‘this‘ keyword stands as a identifier, bridging the gap between functions and their invoking context. This unique identifier grants functions the ability to interact with and manipulate the properties of the object that triggered their invocation, serving as a reference to the current instance or object in control of the ongoing code execution.

The value of ‘this’ depends on how a function is called

  • Global Context: In the global context, ‘this’ refers to the global object which is ‘window’ in the browsers and ‘global’ in Node.js.
  • Function Context: Inside a function, ‘this’ refers to an object that the function is a method of.
  • Constructor Context: When a function is used as a constructor with the ‘new’ keyword ‘this’ refers to a newly created object.
  • Event Handlers: In event handlers, ‘this’ usually refers to an element that triggered the event.
  • Call, Apply, and Bind Methods: The ‘call’, ‘apply’, and ‘bind’ methods allow explicit setting of the value of the ‘this’ when calling a function.

Method Invocation

When a function is invoked as a method of an object this refers to the object that owns the method being called.

Example: Here “this” is accessing the person1 object’s properties.

Javascript
const person1 = {
    name: 'Kumar',
    greet: function() {
        console.log(`Hello, ${this.name}!`);
    }
};
person1.greet();

Output
Hello, Kumar!

Explanation:

  • We define an object person1 with the property name set to ‘Kumar’.
  • Inside person1, we define a method greet which uses a template literal to the log a greeting message including the value of this.name.
  • When we call person1.greet() and this refers to person1 object since greet is invoked as a method of person1.
  • Therefore, the output will be: Hello, Kumar!

Constructor Function:

When a function is used as a constructor with a new keyword this refers to the newly created object instance.

Javascript
function Cars(make, model) {
  this.make = make;
  this.model = model;
  this.displayInfo = function() {
    console.log(`This car is a ${this.make} ${this.model}`);
  };
}
const myCar = new Cars('Toyota', 'TATA');
myCar.displayInfo();

Output
This car is a Toyota TATA

Explanation:

  • The Cars function is defined to the take two parameters: make and model.
  • Inside the function, this refers to current instance being created.
  • The new keyword is used to instantiate a new object of the type Cars.
  • The make parameter is set to the ‘Toyota’ and the model parameter is set to the ‘TATA’.
  • Inside the Cars function, this.make and this.model are used to assign values to properties make and model of newly created object.