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

206
Visualizações
TypeScript scope of keyword 'this'

I have a problem with a scope of keyword 'this'.

The code for instance is:

class Burger {
    
    sleep() {
        // To sleep
    }
    
    pourSauce(sauce: string) {
        // To pour sauce
        this.sleep();
    }
}

class Hesburger extends Burger {
    constructor() {
        super();
    }
    
    private bun: string = 'bunny';
    
    foo(): void {
        this.tmp(this.fat);
    }

    private fat(): void {
        super.pourSauce(this.bun);
    }
    
    private tmp(callBack: () => void): void {
        callBack();
    }
}

Somewhere I call:

Hesburger.foo();

I receive the error:

"bun" is undefined

I have found the post, describing the solution for transmitting a function. But no clue about a class's property.

Can someone advise to transit 'bun' variable's value 'bunny' to function fat(), so it would be transmitted further to function pourSauce()?

Thank you!

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

0

The problem is with the following line

this.tmp(this.fat);

where you are passing the fat function as callback to the tmp function. But eventhough you are passing this.fat it is always just a function, that is not bound to a specific context (ie it does not have a defined this anymore). You can work around this issue by explicitely binding the function to a specific context

this.tmp(this.fat.bind(this))
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