The 'this' Keyword
The value of this depends on how a function is called โ not where it's defined. In the global scope, this refers to window (or global in Node).
console.log(this === window);
function showThis() {
return this;
}
console.log(showThis());
Try it Yourself โ
Object Method Context
When a function is called as a method of an object, this refers to that object.
const person = {
name: "Alice",
greet() {
console.log("Hello, I'm " + this.name);
}
};
person.greet();
const greetFn = person.greet;
greetFn();
Try it Yourself โ
Arrow Functions & this
Arrow functions don't have their own this โ they inherit it from the enclosing lexical scope.
const counter = {
count: 0,
start() {
setInterval(() => {
this.count++;
console.log(this.count);
}, 1000);
}
};
counter.start();
Try it Yourself โ