+ 2
Why cant I call my function in setInterval() inside a class ?
In the code , calling this.update() works normally but not inside a setTimeout() Can anyone tell me why and how to fix it . https://code.sololearn.com/WUi5cd1vF6c2/?ref=app
10 Antworten
+ 5
this is out of scope when use in timer function.
Declare a this var for timer function use.
eg.
var that = this;
setTimeout(function(){
console.log("what")
that.update();
},1000);
+ 5
do this:
var self = this;
//error this.update() is not a function
setTimeout(function(){
console.log("what")
self.update();
},1000);
//************
this inside the setTimeout function is of a different context (it's not the same this)
we have to save it to a variable before and use it then
+ 5
damn Calviղ is a quick one ._.
+ 5
i submit to you oh mighty Calviղ 🙌
+ 5
you earned it >:D
+ 3
The timer function run in separate execution using Window object, so the "this" points to Window global object in timer function.
Btw Utkαrsh the program generates nice effect ☺👍🏼
+ 2
It's my honour to be called mighty by Burey 😁
+ 2
The proper solution is:
setTimeout(function(){
console.log("what")
this.update();
}.bind(this) ,1000);
Simply binding the context of ‘this’ to the function. The bind function returns another function, wrapping the initial one and setting ‘this’ to whatever you supply as a parameter of the bind method.
“var that = this” is frowned upon in industry, but unavoidable in some situations - not this one.
+ 1
Burey 🤣