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

81
Visualizações
typescript external callback binding within classes

I'm trying to bind properties of a class to a callback inside that class.

Quick example:

// caller
const first = (): void => {
  const testClass = new TestClass();
  testClass.second(() => {
    console.log(this.member) // error TS2532: Object is possibly 'undefined'
  }
}

// TestClass
...
member: string = 'test';

second(cb: () => void) {
 const self = this;
 cb.bind(self)();
}

this seems to be possibly undefined.

How can I access the classes members from an outside callback?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The Arrow Functions are for automatic binding to the current scope and parent objects, so you can't call them with bindings of your callbacks. so here javascript interpreter is trying to find the parent which the callback has been defined before.

// caller
const first = (): void => {
  const testClass = new TestClass();
  testClass.second(function() {
    console.log(this.member)
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Add a condition before the console log to avoid print undefined objects.

from your example:

// caller
const first = (): void => {
  const testClass = new TestClass();
  testClass.second(() => {
    if (this.member) console.log(this.member)
  }
}

// TestClass
...
member: string = 'test';

second(cb: () => void) {
   const self = this;
    cb.bind(self)();
}

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