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

195
Visualizações
Why setTimeout doesn't work passing object's metod?

I read lot of topics (here and otherwehere) about setTimeout and this binding. Anyway there's something I need to better understand. I start with below example.

let myObj = {
  p: 'my property',
  m() { console.log(this.p); }
}

setTimeout(myObj.m, 100);  // undefined
setTimeout(function() {myObj.m()}, 100); // 'my property'

What I read from DOC is

Code executed by setTimeout() is called from an execution context separate from the function from which setTimeout was called. The usual rules for setting the this keyword for the called function apply, and if you have not set this in the call or with bind, it will default to the window (or global) object. It will not be the same as the this value for the function that called setTimeout.

And a way to fix using function wrapper

A common way to solve the problem is to use a wrapper function that sets this to the required

as I did in the last statement of the snippet.

My doubt: why passing a method by obj to setTimeout without wrapping it doesn't work? Passing object.method should set this to the object anyway. But maybe the direct setTimeout invocation overrides it, forcing this to be window.

I thought that maybe the use of a wrapper function, creates a new underlying scope that can refer to myObj by closure, and subsequently calling setTimeout(myObj.m(), 100) sets the right this.

Thank in advance

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