JavaScript this Behavior Explained: Understanding Context

🚀 A JavaScript this Behavior That Surprised Me Consider this code: const user = { name: "Inderpal", greet() { console.log(this.name); } }; const greetFn = user.greet; greetFn(); Expected: Inderpal Actual output: undefined Why? Because this in JavaScript is not determined where a function is written. It’s determined by how the function is called. When we did: user.greet() this referred to user. But when we did: const greetFn = user.greet; greetFn(); The function lost its object context. So this became undefined (in strict mode) or the global object. ✅ One way to fix this is using bind: const greetFn = user.greet.bind(user); greetFn(); Now this will always refer to user. In JavaScript, understanding how this works is more important than memorizing syntax. #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering

  • diagram

To view or add a comment, sign in

Explore content categories