Sobes.tech
Junior

Wat is de context in een functie?

sobes.tech AI

Antwoord van AI

De context (this) in een JavaScript-functie wordt bepaald door hoe de functie is opgeroepen, niet door waar deze is gedeclareerd. Het wijst naar het object waar de functie bij hoort of dat het aanroept.

Manieren om de context te bepalen:

  1. Globale context: Buiten functies, of als de functie wordt aangeroepen zonder expliciet object (this is gelijk aan het globale object window in de browser, global in Node.js, of undefined in strict mode).

    // In de browser
    console.log(this === window); // true
    
    function showContext() {
      console.log(this);
    }
    
    showContext(); // window
    
  2. Objectcontext (methode): Als de functie wordt aangeroepen als methode van een object (obj.method()), verwijst this binnen de functie naar dat object.

    const user = {
      name: 'Alice',
      greet: function() {
        console.log(`Hallo, mijn naam is ${this.name}`);
      }
    };
    
    user.greet(); // Hallo, mijn naam is Alice
    
  3. Constructorcontext: Bij het aanroepen van een functie met het sleutelwoord new (new MyClass()), wordt een nieuw object gemaakt, en this binnen de constructor verwijst naar dat nieuwe object.

    function Person(name) {
      this.name = name;
    }
    
    const person1 = new Person('Bob');
    console.log(person1.name); // Bob
    
  4. Expliciete contextaanduiding: Methoden call, apply en bind maken het mogelijk om expliciet de waarde van this in te stellen voor de functieaanroep.

    • call(thisArg, arg1, arg2, ...): Roept de functie aan met this ingesteld op thisArg en argumenten apart.
    • apply(thisArg, [argsArray]): Roept de functie aan met this ingesteld op thisArg en argumenten als array.
    • bind(thisArg, arg1, arg2, ...): Geeft een nieuwe functie terug met this vastgezet op de opgegeven waarde.
    function displayInfo(age) {
      console.log(`${this.name} is ${age} years old.`);
    }
    
    const person = { name: 'Charlie' };
    
    displayInfo.call(person, 30); // Charlie is 30 years old.
    displayInfo.apply(person, [35]); // Charlie is 35 years old.
    
    const bondedDisplayInfo = displayInfo.bind(person, 40);
    bondedDisplayInfo(); // Charlie is 40 years old.
    
  5. Arrow functies: Arrow functies hebben geen eigen this. Ze erven this uit de lexicale omgeving waarin ze zijn gedefinieerd.

    const anotherUser = {
      name: 'David',
      sayHello: function() {
        const innerArrow = () => {
          console.log(`Hallo van arrow, ${this.name}`);
        };
        innerArrow(); // `this` hier is anotherUser, geërfd van sayHello
      },
      sayHelloBad: () => { // slechte praktijk voor objectmethoden
          console.log(`Hallo van arrow, ${this.name}`);
      }
    };
    
    anotherUser.sayHello(); // Hallo van arrow, David
    
    // In de browser, buiten strict-modus
    anotherUser.sayHelloBad(); // Hallo van arrow, undefined (`this` - window)
    

Het begrijpen van de context is cruciaal voor correct werken met objecten, methoden en event handlers in JavaScript.