How is this determined?
MediumJavaScriptthisFunctions
How is the value of this determined in JavaScript? Where do call, apply, bind and arrow functions fit in?
TL;DR
this is decided by how a function is called, not where it's defined. Arrow functions are the exception: they have no this of their own and use the this of the surrounding scope.
Key points
Rules, from highest priority to lowest:
new:thisis the newly created object.- Explicit:
fn.call(obj, a, b),fn.apply(obj, [a, b])orfn.bind(obj)setthistoobj.bindreturns a new function that always uses thatthis. - Method call:
obj.method()setsthistoobj(whatever is left of the dot). - Plain call:
fn()givesundefinedin strict mode (and in modules and classes), or the global object in sloppy mode.
- Arrow functions ignore all four rules and capture
thislexically.call,applyandbindcan't change it. - In DOM listeners with a regular function,
thisis the element.
Example
js
const user = {
name: 'Dana',
greet() {
return this.name
},
}
user.greet() // 'Dana'
const greet = user.greet
greet() // undefined: called without a receiver, so this is lost
greet.call(user) // 'Dana'
class Timer {
seconds = 0
start() {
setInterval(() => this.seconds++, 1000) // arrow keeps the instance's this
}
}Common follow-ups
- Why do callbacks lose
this? Passingobj.methodpasses only the function. Use an arrow wrapper,bind, or a class field arrow function. callvsapply? Same thing;calltakes arguments one by one,applytakes an array.
What interviewers look for
Tip
"It depends on the call site", the four rules in order, and arrow functions as the lexical exception.
- Red flag: "
thisis the object where the function was written."