Losing 'this' When Extracting Methods
What you'll learn: Why storing an object's method in a variable breaks its this binding and causes unexpected behavior.
When you extract a method from an object and store it in a standalone variable, you separate the function from its object. This breaks the method call pattern, causing this to no longer reference the original object.
The Common Pitfall
const person = {
name: 'Alice',
greet: function() {
console.log('Hello, I am ' + this.name);
}
};
person.greet(); // "Hello, I am Alice" ✓
So far, so good. But watch what happens when we extract the method:
const greetFunction = person.greet;
greetFunction(); // TypeError or "Hello, I am undefined"
What Went Wrong?
When you call person.greet(), JavaScript sees the dot (.) and sets this to person. But when you store person.greet in greetFunction, you're just copying the function itself—not the binding.
Calling greetFunction() is now a plain function call, not a method call. There's no dot, no object. In strict mode, this becomes undefined. In non-strict mode, it becomes the global object.
Think of it like this: A method is like a name tag that says "use the object to my left." When you remove it from the object, the name tag has nowhere to point.
Why This Matters
This commonly trips up developers when passing methods as callbacks:
setTimeout(person.greet, 1000); // Broken! 'this' lost
Key Takeaway: Extracting a method into a variable loses its this binding because you're separating the function from the method call syntax that sets this.