JavaScript
Wat is 'this' in JavaScript?
'this' wijst naar het object dat de functie aanroept.
'this' context
In object method: wijst naar het object In functie: wijst naar global (window/global) Arrow functions: inherit 'this' van parent scope .call(), .apply(), .bind() pas 'this' aan
Code Voorbeelden
JAVASCRIPT'this' voorbeelden
const person = {
name: "Jan",
// Regular function - 'this' = person
greet: function() {
console.log(this.name); // "Jan"
},
// Arrow function - 'this' inherit van parent (global!)
greetArrow: () => {
console.log(this.name); // undefined (this != person)
}
};
person.greet(); // "Jan"
// Change 'this' with call/apply/bind
const student = { name: "Maria" };
person.greet.call(student); // "Maria"
// bind creëert nieuwe functie met vaste 'this'
const boundGreet = person.greet.bind(student);
boundGreet(); // "Maria"Relevante trefwoorden
thisbindingcallapplybind