Spot the this Binding Mistake
Question
This code throws an error or gives wrong output. What is the issue?
Code
const obj = {
name: "Ada",
greet() { return "Hello, " + this.name; }
};
const fn = obj.greet;
console.log(fn());
Hint
this depends on how the function is called, not where it is defined.
Explanation
When obj.greet is extracted into fn and called as fn(), this is undefined (in strict mode) or the global object — not obj. So this.name is undefined. The fix is to use .bind(obj): const fn = obj.greet.bind(obj);, or call it as obj.greet() directly, or use an arrow function that captures this lexically.
Related Resources
Related Lessons
- JavaScript Objects
Learn about this binding.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.