Zum Hauptinhalt springen

Das this Schlüsselwort in JavaScript

Das Schlüsselwort this ist in JavaScript von zentraler Bedeutung und zeigt auf den Kontext, in dem eine Funktion aufgerufen wird. Der Wert von this kann je nach Aufrufkontext variieren und hat somit eine besondere Rolle in objektorientierter Programmierung und Event-Handling.

this in einfachen Funktionen

Innerhalb von Funktionen zeigt this im Strict Mode auf undefined. Im Non-Strict Mode zeigt this global auf das window-Objekt.

function simpleFunction() {
console.log(this);
}
simpleFunction(); // -> Im Non-Strict Mode: window, im Strict Mode: undefined

this in Methoden von Objekten

Wenn this in einer Methode eines Objekts aufgerufen wird, zeigt es auf das jeweilige Objekt selbst.

const user = {
name: 'Bob',
greet() {
console.log(`Hallo, mein Name ist ${this.name}`);
}
};
user.greet(); // -> "Hallo, mein Name ist Bob"

this in Konstruktorfunktionen

In Konstruktorfunktionen verweist this auf die neu erstellte Instanz des Objekts.

function Person(name) {
this.name = name;
}
const bob = new Person('Bob');
console.log(Bob.name); // -> "Bob"

this in Arrow Functions

Arrow Functions haben keinen eigenen this-Wert. Stattdessen „erben“ sie this aus dem äußeren Scope, in dem sie definiert wurden.

const team = {
name: 'JavaScript Masters',
members: ['Bob', 'Alice'],
listMembers() {
this.members.forEach(member => console.log(`${member} ist Teil von ${this.name}`));
}
};
team.listMembers();
// -> "Bob ist Teil von JavaScript Masters"
// -> "Alice ist Teil von JavaScript Masters"

this mit Call, Apply und Bind

Mit den Methoden call, apply und bind lässt sich der Wert von this direkt festlegen.

function introduce() {
console.log(`Hallo, mein Name ist ${this.name}`);
}
const person = { name: 'Bob' };

introduce.call(person); // -> "Hallo, mein Name ist Bob"
introduce.apply(person); // -> "Hallo, mein Name ist Bob"

const boundIntroduce = introduce.bind(person);
boundIntroduce(); // -> "Hallo, mein Name ist Bob"

this in Event-Handlern

In Event-Handlern verweist this auf das HTML-Element, das das Event ausgelöst hat.

<button id="clickMe">Click me!</button>
<script>
document.getElementById('clickMe').addEventListener('click', function() {
console.log(this); // -> <button id="clickMe">Click me!</button>
});
</script>

Zusammenfassung:

  • Globale Funktionen: this zeigt auf das window (im Non-Strict Mode) oder ist undefined (im Strict Mode).
  • Methoden in Objekten: this zeigt auf das umgebende Objekt.
  • Konstruktorfunktionen: this zeigt auf die neue Instanz des Objekts.
  • Arrow Functions: this wird vom äußeren Kontext übernommen.
  • Event-Handler: this zeigt auf das HTML-Element, das das Event ausgelöst hat.