JavaScript · The language round
How does this work in JavaScript?
Short answer
this is decided by how a function is called, not where it is defined. Arrow functions are the exception: they capture this from the enclosing lexical scope.
For a normal function, look at the call site. The same function can have a different this depending on how it is invoked.
obj.method()setsthistoobj.- A plain call such as
fn()setsthistoundefinedin strict mode or modules, and to the global object in sloppy mode. fn.call(ctx)andfn.apply(ctx)setthisexplicitly.new Fn()setsthisto the newly created object.- An arrow function ignores all of the above and uses the
thisof the scope where it was written.
const user = {
name: "Asha",
greet() {
console.log(this.name);
},
};
user.greet(); // "Asha"
const greet = user.greet;
greet(); // undefined in strict mode / modules
const bound = user.greet.bind(user);
bound(); // "Asha"Arrow functions
const counter = {
count: 0,
start() {
setTimeout(() => {
this.count++;
console.log(this.count);
}, 100);
},
};
counter.start(); // 1start()'s this. A regular callback would have its own this.This is why arrow functions are a poor choice for object methods or class methods that need the instance, but are a good choice for callbacks inside those methods.
Common mistakes
- Saying
thisrefers to the function itself. It does not. - Assuming an arrow function's
thisdepends on where it is called. - Losing
thiswhen passing a method as a callback withoutbind()or an arrow wrapper.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What do `call`, `apply` and `bind` do?
- 2Why does an arrow function not have its own `this`?
- 3How does `this` behave in a class method?
- 4What happens to `this` when a method is passed as an event handler?
Say it in the interview
For a normal function, `this` is decided at the call site. Calling a method on an object sets `this` to that object; a plain call gives undefined in strict mode; call, apply and bind let you set it explicitly; and new creates a fresh object. Arrow functions are different: they don't have their own this and capture it lexically. That makes arrows good for callbacks inside methods and bad for methods that need the instance.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.