0

I need to call a member function from the callback function in an event listener which is also in another member function. Here is a simplified example:

class C {

  finished() {
    console.log ('over');
  }
  
  timer() {
    console.log('started')
    setTimeout(function fct() {
        this.finished();
    },500);
  }
}


let c = new C();

c.timer();

I get the following result : Uncaught TypeError: this.finished is not a function". I understand that the callback function is no longer member of the class C.

Is there a way to call the finished() member function from the callback function?

Here is a JSFiddle

Fifi
  • 3,360
  • 2
  • 27
  • 53

2 Answers2

2

You need to bind this

class C {
    finished() {
        console.log('over');
    }

    timer() {
        console.log('started');
        setTimeout(function fct() {
            this.finished();
        }.bind(this), 500);
    }
}

let c = new C();
c.timer();

or just hand over the function

this.finished

which keeps the reference of this.

class C {
    finished() {
        console.log('over');
    }

    timer() {
        console.log('started');
        setTimeout(this.finished, 500);
    }
}

let c = new C();
c.timer();
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

this inside the setTimeout callback will refer to window object not the C object, So you need to bind the setTimeout callback with the C object

class C {

  finished() {
    console.log ('over');
  }
  
  timer() {
    console.log('started')
    setTimeout(function fct() {
        // ... some code.
        this.finished();
    }.bind(this),500);
  }
}


let c = new C();

c.timer();

Or you can use the arrow function which will make this will refer to the this of the outer scope.

class C {

  finished() {
    console.log ('over');
  }
  
  timer() {
    console.log('started')
    setTimeout(() => {
        this.finished();
    },500);
  }
}


let c = new C();

c.timer();
Mina
  • 14,386
  • 3
  • 13
  • 26