JavaScript · Question 3 of 50
How is `this` decided in JavaScript?
Whether you know this depends on the call, not on where the function was written (except for arrow functions).
The answer
For a normal function, this is set by how it is called: obj.method() gives obj; a plain call fn() gives undefined in strict mode (the global object in sloppy mode); new Fn() gives the new object; fn.call(x), apply and bind give x.
Arrow functions have no this of their own: they use the this of the code around them. That makes them right for callbacks inside methods and wrong as object methods. The classic bug is passing obj.method as a callback, which loses obj.
const user = {
name: 'Asha',
hi() { return this.name },
}
user.hi() // 'Asha'
const f = user.hi
f() // undefined in strict mode: this is lost
f.call(user) // 'Asha'
setTimeout(user.hi.bind(user))The picture
HOW IT IS CALLED this =
obj.fn() obj
fn() undefined (strict)
new Fn() the new object
fn.call(x) / fn.bind(x) x
() => {} this of the code around itWhy does this break in a React class event handler?
Show the answer
The handler is passed as a bare function, so it is called without its object. Bind it in the constructor or write it as an arrow-function class field.