Programming Languages
JavaScript
Subjective
Sep 25, 2025
What is the this keyword in JavaScript?
Detailed Explanation
The this keyword refers to the object that is executing the current function. Its value depends on how the function is called:
1. Global Context:
console.log(this); // Window object (browser) or global (Node.js)
2. Object Method:
const obj = {
name: "John",
greet() {
console.log(this.name); // "John"
}
};
3. Constructor Function:
function Person(name) {
this.name = name; // refers to new instance
}
4. Arrow Functions:
const obj = {
name: "John",
greet: () => {
console.log(this.name); // undefined (inherits from enclosing scope)
}
};
5. Explicit Binding:
function greet() {
console.log(this.name);
}
greet.call({name: "John"}); // "John"
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts