Pijlfuncties zijn korter, maar de echte verschillen zitten in bindingsgedrag, niet alleen in syntaxis.
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
Pijlfuncties zijn korter, maar de echte verschillen zitten in bindingsgedrag, niet alleen in syntaxis.
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
1. Geen eigen this — pijlfuncties erven this van de omsluitende scope. Dit is het belangrijkste verschil en waarom ze geweldig zijn voor callbacks:
const timer = {
seconds: 0,
start() {
setInterval(() => this.seconds++, 1000); // ✅ `this` is timer
// a regular function here would have its own `this` (undefined) → bug
},
};
2. Geen arguments-object — gebruik rest parameters in plaats daarvan:
const sum = (...args) => args.reduce((a, b) => a + b, 0);
3. Kunnen niet als constructors worden gebruikt — new arrow() werpt een error, en ze hebben geen prototype.
const obj = {
name: "Ann",
greet: () => `Hi ${this.name}`, // ❌ `this` is NOT obj (it's outer scope)
greet2() { return `Hi ${this.name}`; }, // ✅ method needs dynamic `this`
};
Gebruik geen pijlfuncties voor objectmethoden (ze binden niet aan het object) of wanneer je een dynamische this/arguments nodig hebt (event handlers die afhankelijk zijn van this als het element).
Gebruik pijlfuncties voor callbacks en korte functies waarbij het overnemen van this is wat je wilt; gebruik reguliere functies voor methoden, constructors en prototypemethoden.