FrontendAtlas
Interview Questions
Home>JavaScript interview questions> JavaScript coding challenges >Fix lost `this` binding in callback registration

Fix lost `this` binding in callback registration

intermediate
By FrontendAtlas Editorial · Updated Mar 31, 2026
A teammate passes an object method straight into a callback API, assuming it will still remember its owner later. Direct calls like `tracker.recordClick()` work, but the same method breaks once another function invokes it without the original receiver. Fix the bug so registered callbacks keep the right `this`.
Examples
const tracker = createClickTracker('save');
tracker.recordClick(); // 'save:1'
tracker.attach(handler => handler()); // 'save:2'

const tracker = createClickTracker('open');
tracker.attach(handler => [handler(), handler()]); // ['open:1', 'open:2']

Solution

Overview

export default function createClickTracker(label){

return {

label,

count: 0,

recordClick(){

this.count += 1;

return ${this.label}:${this.count};

},

attach(register){

// Detached methods lose their receiver, so bind before handing them off.

return register(this.recordClick.bind(this));

}

};

}

Similar questions

Fix missing return in `map` / `filter`easyFix stale closure in delayed autosave callbackintermediateFix numeric sort in `sortScores`easy

Guides

Frontend interview preparation guideGuideFrontend coding interview questions and prep guideBlueprintJavaScript Problems That Actually Show UpBlueprintBuild Great UI in 60 MinutesBlueprint

Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.

Open frontend interview questionsBrowse JavaScript interview questionsOpen Essential 60Open Machine Coding HubOpen Frontend Coding ChallengesOpen System DesignOpen Interview Prep GuideOpen System Design BlueprintOpen Framework Prep PathsOpen Study PlansOpen JavaScript mastery study planOpen Company PrepOpen JavaScript Framework Prep Guide
↗Incidents hub
← Prev←2 / 8Next →→