Fix lost this binding in callback registration
this binding in callback registrationintermediate
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
1
The fixed code
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
Guides
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
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.