Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!