Explore Library
Code Quiz

Closure Loses this in Prototype Method

A returned inner function references this, but the closure never captured the correct receiver.

Codejavascript
function Counter() {
  this.count = 0;
}

Counter.prototype.makeIncrementer = function () {
  return function () {
    this.count++;
    return this.count;
  };
};

const c = new Counter();
const inc = c.makeIncrementer();
console.log(inc()); // expected 1
console.log(inc()); // expected 2

What is the bug in this code, and how should it be fixed?