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

6.1K
Visualizações
What is 'savedThis' for in the Throttle decorator solution on javascript.info?

On the https://javascript.info/call-apply-decorators there is the solution for the Throttling decorator task. I've modified the code to get rid of 'sevedThis' and it works perfectly without it (even with object methods). Could anybody give a real reason to use 'sevedThis' variable in this case and call 'wrapper.apply(savedThis, savedArgs)' instead of 'wrapper(...savedArgs)'?

Original code:

function throttle(func, ms) {

  let isThrottled = false,
    savedArgs,
    savedThis;

  function wrapper() {

    if (isThrottled) { // (2)
      savedArgs = arguments;
      savedThis = this;
      return;
    }
    isThrottled = true;

    func.apply(this, arguments); // (1)

    setTimeout(function() {
      isThrottled = false; // (3)
      if (savedArgs) {
        wrapper.apply(savedThis, savedArgs);
        savedArgs = savedThis = null;
      }
    }, ms);
  }

  return wrapper;
}

Code without 'savedThis':

 function throttle(func, ms) {
  let isThrottled = false,
    savedArgs;

  function wrapper() {
    if (isThrottled) {
      // (2)
      savedArgs = arguments;
      return;
    }
    func.apply(this, arguments); // (1)
    isThrottled = true;
    setTimeout(function () {
      isThrottled = false; // (3)
      if (savedArgs) {
        wrapper(...savedArgs);
        savedArgs = null;
      }
    }, ms);
  }
  return wrapper;
}
about 4 years ago · Juan Pablo Isaza
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