Sobes.tech
Junior

Wat wordt er weergegeven in de console als je this gebruikt in console.log?

sobes.tech AI

Antwoord van AI

Het hangt af van de context van de aanroep van console.log en de strikte modus van JavaScript ("use strict").

In de globale context (buiten functies en modules):

  • In niet-strikte modus ("use strict" ontbreekt of is gedeclareerd in een functie): this verwijst naar het globale object (window in de browser, global in Node.js).
  • In strikte modus: this is undefined.

Binnen een functie:

  • In niet-strikte modus: this verwijst naar het globale object als de functie als normale functie wordt aangeroepen (myFunction()). Als de functie als methode van een object wordt aangeroepen (myObject.myMethod()), verwijst this naar dat object (myObject). Als de functie wordt gebruikt als constructor (new MyClass()), verwijst this naar het nieuwe object.
  • In strikte modus: this is undefined als de functie als normale functie wordt aangeroepen. In andere gevallen (methode, constructor) is het gedrag hetzelfde als in niet-strikte modus.

Binnen een pijlfunctie (=>):

  • this wordt lexicaal geërfd van de omliggende context. Dit betekent dat de waarde van this binnen een pijlfunctie hetzelfde is als in de externe normale functie of in de globale context waar de pijlfunctie is gedeclareerd, ongeacht hoe deze wordt aangeroepen. Pijlfuncties binden this niet aan hun eigen context.

Voorbeeld:

// Globale context
console.log(this); // In de browser: Window, in Node.js: global (niet-strikte modus)
                    // In de browser: undefined, in Node.js: undefined (strikte modus)

// Normale functie
function showThisNonStrict() {
  console.log(this);
}

showThisNonStrict(); // In de browser: Window, in Node.js: global

function showThisStrict() {
  "use strict";
  console.log(this);
}

showThisStrict(); // undefined

const myObject = {
  methodNonStrict: function() {
    console.log(this);
  },
  methodStrict: function() {
    "use strict";
    console.log(this);
  }
};

myObject.methodNonStrict(); // myObject
myObject.methodStrict();   // myObject

// Pijlfunctie
const arrowFunc = () => {
  console.log(this);
};

arrowFunc(); // In de browser: Window, in Node.js: global (erft uit globale context)

const myObjectWithArrow = {
  arrowMethod: () => {
    console.log(this);
  }
};

myObjectWithArrow.arrowMethod(); // In de browser: Window, in Node.js: global (erft uit declaratiecontext)