Sobes.tech
Junior

Wat is het verschil tussen pijlfuncties en gewone functies in JavaScript?

sobes.tech AI

Antwoord van AI

  1. Syntax:
    • Normale functie: function myFunction() { ... }
    • Pijl functie: () => { ... } of param => { ... }
  2. this-context:
    • Normale functie: this wordt bepaald door de aanroepcontext.
    • Pijl functie: this wordt lexicaal geërfd uit de omringende scope (heeft geen eigen this).
  3. Constructors:
    • Normale functie: Kan als constructor worden gebruikt (new myFunction()).
    • Pijl functie: Kan niet als constructor worden gebruikt.
  4. arguments-object:
    • Normale functie: Heeft zijn eigen arguments-object met de doorgegeven argumenten.
    • Pijl functie: Heeft geen eigen arguments-object, toegang wordt verkregen via rest-parameters (...args).
  5. Genummerde functies:
    • Normale functie: Kan een naam hebben (function myFunction() { ... }).
    • Pijl functie: Standaard anoniem, wordt toegewezen aan een variabele (const myFunction = () => { ... }).
  6. Impliciete return:
    • Normale functie: Vereist expliciet return om een waarde terug te geven (behalve in eenvoudige gevallen zoals IIFE).
    • Pijl functie: Kan bij éénregelige body impliciet het resultaat van een uitdrukking retourneren zonder return.

Vergelijkingstabel:

Kenmerk Normale functie Pijl functie
Syntax function name() { ... } () => { ... }
this-context Dynamisch (afhankelijk van de aanroep) Lexicaal (uit bovenliggende scope)
Constructor Ja Nee
arguments-object Ja Nee (gebruikt rest-parameters)
Naamgeving Kan benoemd zijn Anoniem (toewijzen aan variabele)
Impliciete return Nee (meestal vereist return) Ja (voor éénregelige body)
// Voorbeeld van normale functies
function standardFunction() {
  console.log(this); // Afhankelijk van de aanroepcontext
  console.log(arguments); // `arguments`-object beschikbaar
}

const obj = {
  method: standardFunction
};

standardFunction(); // `this` is window (in browser) of undefined (in strict mode)
obj.method(); // `this` is obj
new standardFunction(); // `this` is nieuw object

// Voorbeeld van pijl functies
const arrowFunction = () => {
  console.log(this); // Erft `this` uit de omringende scope (bijv. Global of module)
  // console.log(arguments); // Fout, `arguments` niet beschikbaar
};

const outerObj = {
  outerMethod: function() {
    const innerArrowFunction = () => {
      console.log(this); // Erft `this` van outerMethod (dat is outerObj)
    };
    innerArrowFunction();
  }
};

arrowFunction(); // `this` is window of {} (in Node.js)
outerObj.outerMethod(); // `this` in innerArrowFunction is outerObj

// Impliciete return in pijl functie
const sum = (a, b) => a + b;
console.log(sum(2, 3)); // 5

// Normale functie met expliciete return
function multiply(a, b) {
  return a * b;
}
console.log(multiply(2, 3)); // 6

// Pijl functie kan niet als constructor worden gebruikt
// new arrowFunction(); // Fout: TypeError: arrowFunction_1 is geen constructor