Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!