Background running and variables

Hi all. I need help.

Something is not evident to me about scope of variables in typescript.

I have an app that goes in background, and with a timer has to check a condition. But with setInterval
I can’t pass a value to the function, and the function can’t access the foreground environment (I guess).

Example (I hope I didn’t big error, this s a not tested code):

export class HomePage {
value: string

    private alertCtrl: AlertController,t,
    private platform: Platform
  ) {
        this.value = "something";
        setInterval(this.test, 1000);

test() { 

console show undefined. Why??

Any help will be appreciated.

This is one of the extremely poor design decisions of JavaScript. The main heuristic I use to avoid problems like you are seeing is “never type the word function inside of one”, and your situation is a cousin of that. In C++, the compiler would throw an error until you made test a static method, at which point it would become obvious to you that you can’t access member variables. JavaScript, on the other hand, decided it would be a better idea to silently make the construct do something nobody would ever expect or want. Your best tool here is the arrow function:

setInterval(() => this.test(), 1000);
1 Like