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):thisverwijst naar het globale object (windowin de browser,globalin Node.js). - In strikte modus:
thisisundefined.
Binnen een functie:
- In niet-strikte modus:
thisverwijst 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()), verwijstthisnaar dat object (myObject). Als de functie wordt gebruikt als constructor (new MyClass()), verwijstthisnaar het nieuwe object. - In strikte modus:
thisisundefinedals de functie als normale functie wordt aangeroepen. In andere gevallen (methode, constructor) is het gedrag hetzelfde als in niet-strikte modus.
Binnen een pijlfunctie (=>):
thiswordt lexicaal geërfd van de omliggende context. Dit betekent dat de waarde vanthisbinnen 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 bindenthisniet 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)