JavaScript Interview Question: How Does "this" Work?
Short answer: for regular functions, this is decided by how the function is called, not where it's defined. Arrow functions don't have their own this; they use the this of the surrounding scope.
The rules, in order
- new:
new User()-thisis the new object. - Explicit:
fn.call(obj),fn.apply(obj),fn.bind(obj)-thisisobj. - Method call:
obj.fn()-thisisobj. - Plain call:
fn()-undefinedin strict mode and modules (the global object in old sloppy-mode scripts).
const user = {
name: 'Asha',
greet() { return `Hi, ${this.name}`; },
};
user.greet(); // 'Hi, Asha'
const greet = user.greet;
greet(); // TypeError in strict mode: this is undefined
greet.call({ name: 'Ravi' }); // 'Hi, Ravi'
The lost-this bug
class Timer {
seconds = 0;
start() {
setInterval(function () { this.seconds++; }, 1000); // 'this' is not the Timer
setInterval(() => { this.seconds++; }, 1000); // arrow: uses start()'s this - works
}
}
Arrow functions
- Capture
thislexically, which is perfect for callbacks inside methods. - Bad as object methods that need the object:
{ name: "x", hi: () => this.name }doesn't work. call/bindcan't change an arrow function'sthis.
bind
button.addEventListener('click', this.handleClick.bind(this));
bind returns a new function with this permanently set.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.