Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda