Open In App

What does this mean in JavaScript ?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, this keyword is a special identifier that refers to the context in which a function is invoked. It allows functions to access and operate on the properties of an object that called them providing a way to refer to the current instance or object that owns the currently executing code.

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads