Understanding JavaScript's `this` Context

Understanding the behavior of `this` in JavaScript can be tricky. Here’s a breakdown of the output from the provided code: The output is: ``` undefined Jyoti ``` **Why this output occurs (Step-by-Step):** 1️⃣ **Method reference loses `this`:** When we reference the method like this: ```javascript const fn = user.getName; ``` `fn` becomes a regular function reference and is no longer associated with the `user` object. Thus, when we call: ```javascript fn(); ``` `this` refers to the global object (or `undefined` in strict mode). This is why the output is: ``` fn() → undefined ``` 2️⃣ **`bind` permanently fixes `this`:** When we use `bind`: ```javascript const boundFn = fn.bind(user); ``` It creates a new function where `this` is permanently set to `user`. Therefore, calling: ```javascript boundFn(); ``` results in: ``` boundFn() → "Jyoti" ``` 🔑 **Key Takeaways:** - The value of `this` depends on how a function is called, not where it is defined. - Extracting a method from its object breaks its original context. - `bind` creates a new function with a fixed `this`. - `call` and `apply` set `this` temporarily, while `bind` sets it permanently. Losing the `this` context is a common pitfall in JavaScript development. #JavaScript #InterviewQuestions #FrontendDeveloper #MERNStack #ReactJS #CallBindApply

  • text

To view or add a comment, sign in

Explore content categories