The this Keyword
this refers to the object that is executing the current function. Its value depends on how the function is called, not where it's defined.
Rules (in priority order)
1. new Binding
function User(name) {
this.name = name;
}
const user = new User("Ajay");
console.log(user.name); // "Ajay" — this = new object
2. Explicit Binding — call, apply, bind
function greet() {
console.log(`Hello, ${this.name}`);
}
const obj = { name: "Ajay" };
greet.call(obj); // "Hello, Ajay"
greet.apply(obj); // "Hello, Ajay"
const bound = greet.bind(obj);
bound(); // "Hello, Ajay"
| Method | Arguments | Invokes immediately? |
|---|---|---|
call | (thisArg, a, b, ...) | ✅ |
apply | (thisArg, [a, b, ...]) | ✅ |
bind | (thisArg, a, b, ...) | ❌ returns new function |
3. Implicit Binding — Object method
const obj = {
name: "Ajay",
greet() {
console.log(this.name);
},
};
obj.greet(); // "Ajay" — this = obj (the calling object)
⚠️ Lost binding:
const fn = obj.greet;
fn(); // undefined — this = window/global (or undefined in strict mode)
4. Default Binding — Standalone function
function show() {
console.log(this);
}
show(); // window (browser) / global (Node) — or undefined in strict mode
Arrow Functions & this
Arrow functions do NOT have their own this. They inherit this from the enclosing lexical scope.
const obj = {
name: "Ajay",
greet: () => {
console.log(this.name); // undefined — 'this' is from outer (global) scope
},
delayedGreet() {
setTimeout(() => {
console.log(this.name); // "Ajay" — arrow inherits 'this' from delayedGreet
}, 100);
},
};
Quick Reference
| Context | this value |
|---|---|
| Global (non-strict) | window / globalThis |
| Global (strict) | undefined |
| Object method | The calling object |
call/apply/bind | The explicitly passed object |
new | The new instance |
| Arrow function | Inherited from enclosing scope |
| Event handler (DOM) | The element that fired the event |
Key Takeaways
thisdepends on how the function is called, not where it's written.- Priority:
new> explicit (call/apply/bind) > implicit (object method) > default. - Arrow functions don't have their own
this— they inherit it lexically.