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

249
Vistas
JS Function.prototype.apply() explanation

I'm a bit confused about this example:

Function.prototype.defer = function(ms) {
  let f = this; // I know content of this - it is function f
  return function(...args) {
    setTimeout(() => f.apply(this, args), ms);
  }
};

// check it
function f(a, b) {
  alert( a + b );
}

f.defer(1000)(1, 2);

I know that first this (let f) contains function f, but what about this in returned function? It is undefined as I understand, isn't it (f.apply(undefined, args)) ? If so, why should we use apply and why does it work?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It is undefined as I understand

It is in your example use of of it.

why should we use call and why does it work?

Not sure why you mention call. Maybe you intended apply. The reason is that you don't know know what f is and whether it needs some this binding, which depends on how it is called. It is nice to take that into account and not lose the this binding in the deferred execution.

Here is an example where the user of defer wants to use this:

Function.prototype.defer = function(ms) {
  let f = this;
  return function(...args) {
    setTimeout(() => f.apply(this, args), ms);
  }
};

// check it
function f(a, b) {
  console.log(this + a + b );
}

f.defer(1000).call(3, 1, 2); // 6

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