How does this work? How are arrow functions different?
Try code in the playgroundUnderstand the concept
this is the receiver used when a regular function runs, and its value usually depends on how the function is called. Arrow functions do not create their own this; they use the surrounding one. This matters when a method is passed as a callback and loses its original receiver.
Important ideas
-
A regular function gets
thisfrom how it is called. -
An arrow function uses
thisfrom the surrounding scope. -
callandapplycall a function with a chosenthis;bindreturns a bound function. -
Calling
user.sayName()usesuseras the receiver; extractingconst fn = user.sayNamecan lose that receiver. -
Arrow functions cannot be called with
new, andcallorbindcannot replace their lexicalthis.
Work through the example
'use strict';
const user = {
name: 'Asha',
getName() { return this.name; }
};
const callback = user.getName.bind(user);
console.log(callback()); // Asha- Passing the unbound method as a plain callback would lose
useras the receiver.
Can you explain it without the notes?
How does this work? How are arrow functions different?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
this is the receiver used when a regular function runs, and its value usually depends on how the function is called. Arrow functions do not create their own this; they use the surrounding one. This matters when a method is passed as a callback and loses its original receiver.
Turn this concept into a clear answer.
- Use a regular method for a dynamic receiver and an arrow callback when the surrounding receiver should be kept.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “How does this work? How are arrow functions different?”. Examples are study fragments; framework behavior can depend on your version.