Skip to content
Exercise · Closures and this · lesson 11 of 11

Exercise: methods that keep this

The object counter stores a number in its count property and has two methods. The method inc() adds its own step to this.count and returns the new value. The method reset() writes zero into this.count and returns 0.

Write a function function bindCounter(counter) that returns an object with two functions, inc and reset. Each one calls the method of counter with the same name and returns its result, even when it is called without a dot or passed as a callback.

  • a counter with count equal to 0 and step 1: const inc = bindCounter(counter).inc, then inc() → 1, one more inc() → 2
  • the same kind of counter: [1, 2, 3].forEach(bindCounter(counter).inc), then counter.count → 3
  • const reset = bindCounter(counter).reset, then reset() → 0 and counter.count → 0

Constraints: the step and count are integers from 0 to 100; the methods of counter read and change this.count; every counter object has its own count.

Do not add extra imports unless the task says so explicitly.

bind-counter.js — javascript
javascript · 11 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way