Understanding the this Keyword in JavaScript
Source: Dev.to
Introduction
JavaScript has a special keyword called this that often confuses beginners.
The key idea: this refers to the object that is “calling” the function.
this in the Global Context
In the global scope:
// In a browser → points to `window` object
// In Node.js → points to `global` objectVisual:
Global scope →this = window(browser) /global(Node)
this Inside Objects
When a function is called as a method of an object, this points to that object.
const user = {
name: "Rahul",
greet() {
console.log(`Hello, ${this.name}`);
}
};
user.greet(); // Hello, Rahulthisrefers touserbecauseuseris the caller ofgreet().
Visual Representation
user → greet() → this = userthis Inside Functions
In a regular function:
function sayHello() {
console.log(this);
}
sayHello(); // Global object (window/global) or undefined in strict mode- Here,
thisdoes not point to the function itself; it depends on how the function is called.
Changing Context: call, apply, bind
You can manually set this using the following methods:
const user = { name: "Rahul" };
function greet(age) {
console.log(`${this.name} is ${age} years old`);
}
greet.call(user, 22); // Rahul is 22
greet.apply(user, [22]); // Rahul is 22
const boundGreet = greet.bind(user);
boundGreet(22); // Rahul is 22call→ invoke immediately, arguments passed separatelyapply→ invoke immediately, arguments passed as an arraybind→ returns a new function withthisbound to the specified object
this in Arrow Functions
Arrow functions do not have their own this; they inherit it from the surrounding (lexical) scope.
const user = {
name: "Rahul",
greet: () => {
console.log(this.name);
}
};
user.greet(); // undefined (inherits `this` from global scope, not `user`)Key Takeaways
thisrefers to the caller of the function, not the function itself.- Global context → points to
window(browser) orglobal(Node). - Object method → points to the object calling the method.
- Regular function → global object (or
undefinedin strict mode). - Arrow functions → lexically inherit
thisfrom the surrounding scope.
Context Cheat Sheet
| Context | this Points To |
|---|---|
| Global | window / global |
| Object method | Object calling the method |
| Regular function | Global object (or undefined in strict mode) |
| Arrow function | Surrounding lexical scope |
call/apply/bind | Explicitly set object |