Arrow Functions as Methods
What You'll Learn
You'll discover why using arrow functions as object methods leads to unexpected behavior—and why regular functions are usually the better choice for methods.
The Problem with Arrow Methods
When you define an object method using an arrow function, it won't work the way you expect. Remember: arrow functions capture this from their surrounding lexical scope at the moment they're defined. They don't create their own this binding.
If you write an arrow function as a method inside an object literal, that arrow function doesn't bind this to the object. Instead, it inherits this from the outer scope—often the global scope or undefined (in strict mode).
const user = {
name: 'Alice',
greet: () => {
console.log(`Hello, ${this.name}`);
}
};
user.greet(); // "Hello, undefined"
Even though you called greet() as a method on user, the arrow function's this doesn't refer to user. It refers to whatever this was in the outer scope where the object was created.
When Arrow Methods Break
This becomes especially problematic when you expect normal method behavior:
const counter = {
count: 0,
increment: () => {
this.count++; // 'this' is NOT the counter object
}
};
counter.increment();
console.log(counter.count); // Still 0
The this.count inside increment refers to some outer scope's count property (probably undefined), not counter.count.
The Solution
Use regular function expressions or shorthand method syntax for object methods:
const user = {
name: 'Alice',
greet() {
console.log(`Hello, ${this.name}`); // 'this' is user
}
};
Key Takeaway: Arrow functions capture this lexically from their surrounding scope, so they fail as object methods when you need this to refer to the object itself. Use regular functions for methods instead.