Question Bank
/

JavaScript Lost-this and Four Fixes Quiz

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.

Question Bank
Medium
JavaScript
5 questions
quiz
js-this
js-arrow-functions
interview-prep

173 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.
const obj = {
    x: 1,
    getX() {
        const inner = function () {
            console.log(this.x);
        };
        inner();
    }
};
// rewrite obj so getX prints 1 using an arrow function for inner