How does this work? How are arrow functions different?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn How does this work? How are arrow functions different?
Definition:
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.
Key points:
-
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.
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.
Interview point:
- 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?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.