I'm trying to make a very very simple billiard game to practice JQuery OOP. I'm starting; and I have this code:
//Main ball "class"
function createBall(number, color){
this.number = number;
this.color = color;
}
$color = ["noColor", "yellow","blue","red","purple","orange","green"...];
$ball1 = new createBall(1, $color[1]);
$ball2 = new...
But, I don't want to create an object ball by ball, so I tried to use a for; something that works like this:
for(var $i = 1; $i <= 15; $i++){
ball+$i = new createBall($i, $color[i]);
}
Obviously, I can't name the new object using "ball+$i". I'm trying to achieve this 'cause I want to use later "ball1.color = 'red'..." and change the object property and so.
The way that worked by now is this code:
$ballArray[] = new Array;
for(var $i = 1; $i <= 15; $i++){
$ballArray[$i] = new createBall($i, $color[i]);
}
If I call $ballArray[1].color, it returns "yellow", as should be; but I'm not sure if "$ballArray[1]" is actually the object name, or if this calls the createBall() function each time I 'call' this object properties and generate a new one. This probably could create tons of objects, and that's a NOPE. Am I doing it right? Or is there another way to correctly do this?
In the end, I just want to create and name all the balls objects without doing it one by one, in case I need to create 100 objects later.
Hope I have explained correctly. All suggestions are welcome :)
newis called once per array object in your code.newreturns an instance ofcreateBall, which is stored in the array. When you want to store a number of items of the same kind, an array is usually the right call. By the way, to follow OOP, your class should probably be calledBall, notcreateBall. The creation is happening innewand the object is aBall.for (var $i = 0; $i < 15; $i++)and then say$ballArray[$i] = new createBall($i + 1, $color[$i]);. As for your question about it being the object name, i'm not sure what you're asking, but I can say that any time you use thenewkeyword, it will return you an object. So in this case, each element of$ballArraywill actually be a ball object with the properties specified upon creation.Balland notcreateBall.createBallcan be a function that returnsnew Ball(number, color), but the class itself should be calledBall. I ran out of characters to mention that xD[]as a part of your variable name for$ballArray, in Javascript you would simply say$ballArray = new Array, or alternatively$ballArray = [];Side note - none of this is jQuery code, this is all plain JavaScript