cj p cj p - 14 days ago 7
Javascript Question

using a setInterval within a class and then making multiple of those classes javascript

So I have a class with a loop in it that I want to run every 50 milliseconds but with using setInterval you can't do this.loop() because then its trying to find loop() from with in the setInterval function but not the class so I did

self=this
then
setinterval(function(){self.loop()})
which work all well and good untill i made 2 of them so then only one of them had the loop running

code:

enemy = function(){
self=this
setinterval(function(){self.loop()})

this.loop=function(){
code
}
}

enemy1 = new enemy
enemy2 = new enemy


so how can i have so enemy1 and 2 have the loop working and not just enemy2

Answer

You are missing variable declarations with var everywhere.

What it means is that global variables are created. It's not critical for enemy, enemy1 and enemy2 variables.

But the variable self becomes shared for all instances.

So the fix: always declare your variables with var.

References: