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
2
Answers
You need to bind
this
or just hand over the function
which keeps the reference of
this
.this
inside thesetTimeout
callback will refer towindow
object not theC
object, So you need tobind
thesetTimeout
callback with theC
objectOr you can use the arrow function which will make
this
will refer to thethis
of the outer scope.