Fix lost `this` binding in callback registration
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.Solution idea
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));
}
};
}
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
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.