How do I bind an object method to its context if the object method is passed to a function as an argument
I have an object with a method that I want to pass to a special function. The job of this special function is to call the function passed as an argument and also to save all the arguments passed to the executed/returned/called function to an external variable.
const playerPerformance = {
goals: 18,
assists: 19,
total(penalties, tackles) {
return this.goals + this.assists + penalties + tackles;
},
};
const calls = [];
function saveCalls(func) {
return withMemory = (...rest) => {
calls.push(rest);
return func(...rest);
};
};
const tester = saveCalls(playerPerformance.total);
The problem is that I do not know how to save the context of the passed function. It must be done inside the function saveCalls
, not like this const tester = saveCalls(playerPerformance.total.bind(playerPerformance);
. I tried applying the methods bind(), call(), apply()
inside saveCalls
but this does not work this way.
The current result:
tester(2,1) // NaN
...which is understandable as I lose a context, and I get undefined + undefined + 2 + 1
The wanted result after this code change:
tester(2,1) // 40
Solution 1:
Just make a wrapper function, that makes provides right this
argument to total
. The bind
method is designed for this:
const tester = saveCalls(playerPerformance.total.bind(playerPerformance));