Fix lost `this` binding in callback registration

intermediate
By FrontendAtlas Editorial · Updated Oct 5, 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.

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));

}

};

}

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']