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
counterwithcountequal to0and step1:const inc = bindCounter(counter).inc, theninc()→1, one moreinc()→2 - the same kind of
counter:[1, 2, 3].forEach(bindCounter(counter).inc), thencounter.count→3 const reset = bindCounter(counter).reset, thenreset()→0andcounter.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.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.