First of all, I know that there are many closing questions in JavaScript, especially when it comes to loops. I read many of them, but I just can't figure out how to fix my own problem. My main experience is C #, C ++, and some ASMs, and it gets a little used to JavaScript.
I am trying to populate a 3-dimensional array with new instances of the class (called Tile) in some for loops. All I want to do is pass a reference to some other class (called Group) that is created in the first loop (and also added to another array). As you might have guessed, after the cycles are completed, each instance of the Tile class has a reference to the same Group object, namely the last one to be created.
Apparently, instead of passing a reference to the Group object, a reference is passed to some variable local to the function, which is updated at each iteration of the loop. My assumption is that the solution to this problem has something to do with closure, as it seems to be related to many of the similar problems that I encountered in finding a solution.
I posted some abbreviated code that reveals the essence of the problem on jsFiddle :
//GW2 namespace (function( GW2, $, undefined ) { //GW2Tile class GW2.Tile = function(globalSettings, kineticGroup) { //Private vars var tilegroup = kineticGroup; // console.log(tilegroup.grrr); //Shows the correct value var settings = globalSettings; this.Test = function(){ console.log(tilegroup.grrr); } this.Test2 = function(group){ console.log(group.grrr); } } //Class }( window.GW2 = window.GW2 || {}, jQuery )); var zoomGroups = []; var tiles = []; var settings = {}; InitArrays(); tiles[0,0,0].Test(); //What I want to work, should give 0 tiles[0,0,0].Test2(zoomGroups[0]); //How I'd work around the issue function InitArrays(){ var i, j, k, zoomMultiplier, tile; for(i = 0; i <= 2; i++){ zoomGroups[i] = {}; zoomGroups[i].grrr = i; tiles[i] = []; zoomMultiplier = Math.pow(2, i); for(j = 0; j < zoomMultiplier; j++){ tiles[i,j] = []; for(k = 0; k < zoomMultiplier; k++){ tile = new GW2.Tile(settings, zoomGroups[i]); tiles[i,j,k] = tile; } } } }
Until now, when working with JavaScript, I usually twisted the code a bit to make it work, but I was tired of using workarounds that seem messy, since I know that there really needs to be a fairly simple solution, I just don't like asking for help, but it really makes my head. Any help is greatly appreciated.