Study notes · 12% of the exam
this and Binding
`this` is decided by how a function is called, except in arrow functions, which inherit it.
Key points
- 1
Method call
obj.fn()setsthistoobj. A plain callfn()sets it toundefinedin strict mode (modules and classes are always strict). - 2
callandapplyinvoke immediately with a chosenthis;bindreturns a new function withthisfixed. - 3
Arrow functions have no
thisof their own; they use the surrounding scope's, so they suit callbacks inside methods. - 4
new Fn()creates a fresh object and bindsthisto it.
Common traps
Passing
obj.methodas a callback (tosetTimeoutor an event listener) losesthisunless you bind it or wrap it in an arrow function.
Read the source
Further reading
Suggest a resource- javascript.info: Object methods, "this"(opens in a new tab)How this is set by the call, and what happens when a method is detached.Articlejavascript.infoEditor’s pick
- javascript.info: Arrow functions revisited(opens in a new tab)Why arrow functions have no own this or arguments.Articlejavascript.infoEditor’s pick
Test yourself on this and Binding
Ten questions, with the answer and explanation after each one.