SOLVED - This example code worked, so I compared it to the non-working I had and found a discrepancy.
In my code, the one that did not work, when declaring the color array I forgot to add a "var" before it.
m_color = [];
m_color[0] = 255;
m_color[1] = 255;
m_color[2] = 255;
m_color[3] = 255;
instead of:
var m_color = [];
m_color[0] = 255;
m_color[1] = 255;
m_color[2] = 255;
m_color[3] = 255;
That's it. No error was generated and I guess it created it as a global array shared by all the particles.
Thanks for the answers everyone. I will use them to write better javascript code.
Old question (which is no longer relevant) is below:
I have this crazy issue with javascript arrays scope.
I have a class Particle:
function ParticleClass()
{
var m_color = [];
m_color[0] = 255;
m_color[1] = 255;
m_color[2] = 255;
m_color[3] = 255;
var m_red = 255;
var m_green = 255;
var m_blue = 255;
this.SetRandomColorRGB = SetRandomColorRGB;
this.SetRandomColorArray = SetRandomColorArray;
this.DrawParticleRGB = DrawParticleRGB;
this.DrawParticleArray = DrawParticleArray;
function SetRandomColorRGB()
{
m_red = Math.floor( Math.random() * 255 );
m_green = Math.floor( Math.random() * 255 );
m_blue = Math.floor( Math.random() * 255 );
}
function SetRandomColorArray()
{
m_color[0] = Math.floor( Math.random() * 255 );
m_color[1] = Math.floor( Math.random() * 255 );
m_color[2] = Math.floor( Math.random() * 255 );
}
function DrawParticleRGB( ctx )
{
// I draw the particle using m_red, m_green and m_blue.
}
function DrawParticleArray( ctx )
{
// I draw the particle using m_color[0], m_color[1], m_color[2]
}
}
I then create an array of ParticleClass particles and draw them.
If I create a bunch of particles and try to draw them on the screen, SetRandomColorRGB and DrawParticleRGB works great. Each particle has a different color.
If I use SetRandomColorArray and DrawParticleArray, all the particles have the same color. Each time a new particle is created, all the particles change to the last color SetRandomColorArray picked.
It looks to me that arrays share memory, whereas other variables do not. Is this true? Is this a quirk of Javascript? Is something else going on?
Thanks.
here... this may help explain why it is happening :
There's no problem with the code you posted, but having said that, you're making life more difficult by doing it this way; it's better to make proper use of prototypes:
The variable's scope is within function ParticleClass(). So variables in functions defined in this space will share the scope with its parent..
This is why sometimes you see this pattern in Javascript -
Why don't you use prototype to define to the functions...
E.g..
This will get you the namespace you want...
Here's an example: http://jsfiddle.net/RvCgJ/