Definition
The this keyword in JavaScript refers to the object that is executing the current function. Its value is determined by how a function is called.
Key Points
- Context-sensitive: depends on execution context.
- Global context: refers to global object (window in browser).
- Function context: refers to global object (non-strict) or undefined (strict).
- Object context: refers to the object calling the method.
- Constructor functions: refers to the newly created object.
- Arrow functions: inherit
thisfrom surrounding scope.
Why this is Needed
It allows functions and methods to operate on the object they belong to, making code reusable and dynamic.
Syntax
// Inside a method
object.method() {
console.log(this);
}
// Inside a constructor
function Person(name) {
this.name = name;
}
// Arrow function (lexical this)
let arrowFunc = () => console.log(this);
Examples
1. Global Context
console.log(this); // Window object in browser
2. Function Context
function showThis() {
console.log(this);
}
showThis(); // Window (non-strict) or undefined (strict)
3. Object Method
const person = {
name: "Sudhanshu",
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // Hello, Sudhanshu
4. Constructor Function
function Person(name, age) {
this.name = name;
this.age = age;
}
const p1 = new Person("Sudhanshu", 21);
console.log(p1.name); // Sudhanshu
5. Arrow Function
const obj = {
name: "Sudhanshu",
greet: function() {
const arrowFunc = () => console.log(this.name);
arrowFunc();
}
};
obj.greet(); // Sudhanshu
6. call, apply, bind
function sayHello(city) {
console.log(`Hello, I am ${this.name} from ${city}`);
}
const person = { name: "Sudhanshu" };
sayHello.call(person, "Delhi"); // Hello, I am Sudhanshu from Delhi
sayHello.apply(person, ["Mumbai"]); // Hello, I am Sudhanshu from Mumbai
const boundFunc = sayHello.bind(person, "Kolkata");
boundFunc(); // Hello, I am Sudhanshu from Kolkata
Where this is Used
- Object-oriented programming
- Constructor functions and classes
- Event handling
- Callback functions
- Libraries and frameworks (React, jQuery)
Summary
thisis dynamic; depends on function call.- Global scope → global object
- Object method → the object itself
- Constructor → new instance
- Arrow function → inherits
this - Can be explicitly set with
call,apply, orbind