Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda