Question Bank
JavaScript Lost-this and Four Fixes Quiz
Difficulty: Medium
Repair a method whose inner regular function loses `this`, four ways (arrow function, `bind`, save-this-in-self pattern, explicit `.call`), plus an explainer on lexical-vs-dynamic this binding.
JavaScript Lost-this and Four Fixes Quiz
Repair a method whose inner regular function loses `this`, four ways (arrow function, `bind`, save-this-in-self pattern, explicit `.call`), plus an explainer on lexical-vs-dynamic this binding.
172 views
3
Fix the lost-this bug below by rewriting the inner function as an arrow function so it captures the enclosing method's this. Return the patched object literal.
Examples
Example 1:
Input:
const obj = { x: 1, getX() { const inner = function () { console.log(this.x); }; inner(); } };
obj.getX();
Output before fix: undefined
Output after fix: 1
Explanation: Arrow functions do not get their own `this`; they reuse the surrounding lexical one.Fix the lost-this bug in the snippet below by keeping the inner regular function and pinning its this with Function.prototype.bind. Show both shapes: binding at call time, and binding once at assignment time.
Examples
Example 1:
Input: the object literal in the code stem above
Output after fix: 1
Explanation: bind(this) returns a new function permanently locked to the supplied receiver.Fix the lost-this bug in the snippet below using the classic save-this-in-self pattern (const that = this). The inner regular function then closes over that instead of referencing this. Explain in your solution comment why this still works in legacy ES5 environments where arrow functions are unavailable.
Examples
Example 1:
Input: the object literal in the code stem above
Output after fix: 1
Explanation: `that` is a regular variable captured by the closure; no this-binding magic required.Fix the lost-this bug in the snippet below by invoking the inner regular function with Function.prototype.call, passing the enclosing this as the explicit receiver. Then explain when .apply would be the more natural choice over .call.
Examples
Example 1:
Input: the object literal in the code stem above
Output after fix: 1
Explanation: `.call(this)` invokes inner with the outer `this` as its receiver.Explain the difference between LEXICAL and DYNAMIC this binding in JavaScript, and rank these four fixes (arrow function, bind, save-this-in-self, explicit .call) by which category they belong to. No code required; one or two paragraphs is enough.
