In JavaScript, the this keyword refers to the object that the current function or method is a property of. The value of this is determined at runtime and depends on how the function or method is invoked.
There are several use cases for the this keyword in JavaScript:
-
Method Invocation:
When a function is invoked as a method of an object,
thisrefers to the object itself.For example:
const person = { name: "John Doe", greeting: function () { console.log(`Hello ${this.name}`); }, }; -
Constructor Invocation:
When a function is used as a constructor with the
newkeyword,thisrefers to the new object being constructed.For example:
function Person(name) { this.name = name; this.greeting = function () { console.log(`Hello ${this.name}`); }; } const person = new Person("John Doe"); person.greeting(); -
Function Invocation:
When a function is invoked as a standalone function,
thisrefers to the global object (windowin browsers, orglobalin Node.js).For example:
function greeting() { console.log(`Hello ${this.name}`); } greeting(); -
Call and Apply Invocation:
When a function is invoked using the
callorapplymethod,thisrefers to the first argument passed to the method.For example:
const person1 = { name: "Jane", greeting: function () { console.log(`Hello ${this.name}`); }, }; const person2 = { name: "John Doe", }; person1.greeting.call(person2); // Hello John Doe -
Arrow Functions:
In arrow functions,
thisis inherited from the surrounding scope.This means that the value of
thisin an arrow function is the same as the value ofthisin the outer function.For example:
const person = { name: "John Doe", greeting: () => { console.log(`Hello ${this.name}`); }, }; person.greeting(); // Hello undefined
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.