JavaScript this Keyword
The `this` keyword refers to the object that is currently executing the function. Its value depends on HOW a function is called, not where it's defined.
In a regular method call, `this` is the object before the dot. In a standalone function call (non-strict mode), `this` refers to the global object. Arrow functions don't have their own `this` โ they inherit it from their surrounding scope.
this in methods
`obj.method()` sets `this` to obj inside method. Calling the same function detached from obj loses that binding.
this in arrow functions
Arrow functions capture `this` from their enclosing lexical scope at definition time, which makes them ideal for callbacks inside methods.
let obj = {
name: "Kai",
greet() { return "Hi " + this.name; }
};
console.log(obj.greet());Hi Kaithis refers to obj because greet was called as obj.greet().
let obj = {
name: "Kai",
delayedGreet() {
let arrow = () => "Hi " + this.name;
return arrow();
}
};
console.log(obj.delayedGreet());Hi KaiThe arrow function inherits this from delayedGreet's scope.
Key points
- this depends on how a function is called, not where it's defined.
- In a method call, this refers to the object before the dot.
- Arrow functions inherit this from their enclosing scope.
- call(), apply(), and bind() let you explicitly set this.
