Recent Post:
Categories:
In JavaScript, the this keyword is a special identifier that refers to the context in which a function is called. Its value can change depending on how a function is invoked. Understanding this is crucial for writing clear and effective JavaScript code.
In the global context (outside of any function), this refers to the global object. In browsers, this is the window object.
code
console.log(this); // In a browser, this will log the window object
When used inside a regular function, this refers to the global object (in non-strict mode). In strict mode, it will be undefined.
code
function showThis() {
console.log(this);
}
showThis(); // Output: Window object (non-strict mode)
code
"use strict";
function showThis() {
console.log(this);
}
showThis(); // Output: undefined
When a function is called as a method of an object, this refers to that object.
code
const person = {
name: "Satyendra",
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // Output: Hello, Satyendra
Here, this inside the greet method refers to the person object, allowing access to its properties.
When a function is used as a constructor (invoked with the new keyword), this refers to the newly created object.
code
function Person(name) {
this.name = name;
}
const person1 = new Person("Satyendra");
console.log(person1.name); // Output: Satyendra
Arrow functions do not have their own this. Instead, they inherit this from the surrounding lexical context.
code
const person = {
name: "Satyendra",
greet: function() {
const innerFunction = () => {
console.log("Hello, " + this.name);
};
innerFunction();
}
};
person.greet(); // Output: Hello, Satyendra
The innerFunction is an arrow function, so it inherits this from the greet method, which is the person object.
You can explicitly set the value of this using call(), apply(), or bind().
code
function greet() {
console.log("Hello, " + this.name);
}
const person1 = { name: "Satyendra" };
const person2 = { name: "John" };
greet.call(person1); // Output: Hello, Satyendra
greet.call(person2); // Output: Hello, John
code
const person = { name: "Satyendra" };
const greet = function() {
console.log("Hello, " + this.name);
}.bind(person);
greet(); // Output: Hello, Satyendra
The this keyword refers to the context in which a function is called, not where it is defined.
Its value varies depending on the invocation context: global, object method, constructor function, or arrow function.
You can control this using call(), apply(), and bind().