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,
this
refers 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
new
keyword,this
refers 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,
this
refers to the global object (window
in browsers, orglobal
in Node.js).For example:
function greeting() { console.log(`Hello ${this.name}`); } greeting();
-
Call and Apply Invocation:
When a function is invoked using the
call
orapply
method,this
refers 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,
this
is inherited from the surrounding scope.This means that the value of
this
in an arrow function is the same as the value ofthis
in 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.