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
Test yourself on this and Binding
Ten questions, with the answer and explanation after each one.