In this article we will see What is the use of the “this” keyword in JavaScript?
In JavaScript, the ‘this’ keyword is a reference to the object that owns the code that is currently being executed. It allows you to refer to properties and methods of the current object within its scope.
The value of ‘this’ depends on how a function is called or how an object is accessed. When a function is called as a method of an object, ‘this’ refers to the object that the method belongs to. For example:
const person = { firstName: 'John', lastName: 'Doe', fullName() { return `${this.firstName} ${this.lastName}`; } }; console.log(person.fullName()); // output: John Doe
In the above example, ‘this’ refers to the ‘person’ object because ‘fullName()’ is called as a method of ‘person’.
When a function is called standalone, ‘this’ refers to the global object (window in a web browser, or global in Node.js). In strict mode, ‘this’ is undefined in a standalone function.
For example:
function greeting() { console.log(this); } greeting(); // output: Window (or global in Node.js)
You can also use the ‘call()’, ‘apply()’, or ‘bind()’ methods to set the value of ‘this’ explicitly within a function.
For example:
const person = { firstName: 'John', lastName: 'Doe' }; function fullName() { return `${this.firstName} ${this.lastName}`; } console.log(fullName.call(person)); // output: John Doe
In the above example, the ‘call()’ method sets the value of ‘this’ to the ‘person’ object, so ‘fullName()’ returns the full name of the ‘person’.