Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda