How does `this` work in JavaScript?
this is decided by how a function is called, not where it is written. Arrow functions are the exception.
The rules, from highest priority
- new binding:
new Fn()setsthisto the newly created object. - Explicit binding:
fn.call(obj),fn.apply(obj, args)orfn.bind(obj)setthistoobj. - Implicit binding:
obj.method()setsthistoobj(the object before the dot). - Default binding: a plain call
fn()givesundefinedin strict mode (modules and classes are always strict) or the global object in sloppy mode.
Arrow functions
Arrow functions have no own this. They use this from the surrounding scope at creation time, and call/bind cannot change it. That is why arrows are ideal for callbacks inside methods, and wrong as object methods.
Losing this
Passing a method as a callback detaches it from its object: setTimeout(obj.method) calls it as a plain function. Fix with obj.method.bind(obj), an arrow wrapper, or a class field arrow function.
Example
const user = {
name: 'Asha',
greet() { return `Hi ${this.name}`; },
greetLater() { setTimeout(() => console.log(this.greet()), 0); }, // arrow keeps this = user
};
console.log(user.greet()); // Hi Asha (implicit)
const loose = user.greet;
// loose(); // TypeError in strict mode: this is undefined
console.log(loose.call({ name: 'Ravi' })); // Hi Ravi (explicit)
user.greetLater(); // Hi AshaFollow-up questions interviewers ask
Try answering each one before you open it.
What does bind return and can you bind twice?
bind returns a new bound function with this (and optionally leading arguments) fixed permanently. Binding a bound function again does not change this; only extra arguments are added. The one thing that overrides a bound this is calling it with new.