this, call, apply & bind — JavaScript interview guide
this, call, apply & bind
The value of this depends on HOW a function is called. call, apply and bind let you choose this yourself.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
Where does "this" point?
▶const user = {2name: "Sumit",3greet() {4return this?.name;5},6};78console.log(user.greet());9const fn = user.greet;10console.log(fn());11console.log(fn.call(user));12const bound = fn.bind(user);13console.log(bound());
| user | { name, greet } |
nothing printed yet
What happens:The user object is created with a name and a greet method.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
The rules, in order
1. new Fn() → this is the new object.
2. fn.call/apply/bind(obj) → this is obj.
3. obj.fn() → this is obj (the thing before the dot).
4. fn() → undefined in strict mode/modules, window in old sloppy scripts.
Arrow functions ignore all of these: they take this from the surrounding code.
call vs apply vs bind
call and apply run the function immediately. bind returns a new function for later.
function intro(city, role) {
return this.name + " from " + city + ", " + role;
}
const me = { name: "Sumit" };
intro.call(me, "Noida", "Dev"); // args one by one
intro.apply(me, ["Noida", "Dev"]); // args as array
const later = intro.bind(me, "Noida");
later("Dev"); // runs later, this lockedRemember this
- Look at the call site to find this.
- Passing obj.method as a callback loses this — fix with bind or an arrow function.
- Arrow functions are great inside methods (for callbacks) but bad AS object methods.
Interview questions
Difference between call, apply and bind?
call(thisArg, a, b) and apply(thisArg, [a, b]) invoke immediately; bind(thisArg, ...args) returns a new function with this permanently set.
What is this inside an arrow function?
Arrow functions do not have their own this. They use this from the enclosing lexical scope, and call/apply/bind cannot change it.
Practice
- Write Function.prototype.myBind.
- Write myCall without using call or apply.
Keep learning
More in Functions & Objects