ZAR
ZAR

Reputation: 2736

Javascript: Instantiating new object from it's own recursion

I'd like to be able to create a function that returns a grid of parameter defined size and inserts parameter defined data into the grid's 'cubbies'. For instance:

function createGrid(rows, cols, data){

var customGrid = [];

//create grid
for(row=0;row<rows;row++){
       var customRow = [];
       for(col=0;col<cols;col++){ 

               //dataFunction can accept different types of data
               if(typeof dataFunction == 'function'){//alert("was function");
                    data = dataFunction();
               }
               //Here lies our problem, I think:
               else if(typeof dataFunction == 'object'){alert("was object");
                   data = new dataFunction(); alert("was object");
               }

               else{//alert("was else");
                   data = dataFunction;
               }

             customRow.push(data);

       }
       customGrid.push(customRow);
}

return customGrid;

}

Furthermore, I'd like to be able to call createGrid() on itself so that we can have grids within grids. Something like this: createGrid(1,2,createGrid(2,2,createObj))

When I do this, the first grid (the 2x2 with an obj inside) is called and successfully creates a new 2x2 grid, each with a unique object. I would like this process to repeat itself for the next 'cubby' of the larger grid (the 1x2 grid), but instead since it is now fed (via dataFunction) an object, it just provides a reference to the first grid in the next cubby.

What I would like:

-------------
||obj1|obj2||
||---------||
||obj3|obj4||
-------------
||obj5|obj6||
||---------||
||obj7|obj8||
-------------

What happens instead:

-------------
||obj1|obj2||
||---------||
||obj3|obj4||
-------------
||obj1|obj2||
||---------||
||obj3|obj4||
-------------

I'm hoping there is a way to re-instantiate dataFunction so that the next iteration of the larger grid called a whole new version of itself so that the second 'cubby' contained a whole new grid.

Any thoughts?

Thank you.

Upvotes: 0

Views: 102

Answers (1)

Bergi
Bergi

Reputation: 664640

Something like this: createGrid(1,2,createGrid(2,2,createObj)) - [but] it just provides a reference to the first grid in the next cubby.

Same problem as last time: You're passing a reference to the one constructed grid, which will then be referenced from all new cubbies - it will alert("was object"); and objects are copied by reference.

If you want an instantiation to happen for each constructed cell, then you will need to pass a function for the dataFunction parameter again:

createGrid(1,2,function() {
    return createGrid(2,2,createObj);
})

Also notice that if (typeof dataFunction == 'object') data = new dataFunction(); is rubbish. You can use new only on constructor functions, whose typeof is 'function'. Otherwise (when dataFunction is not constructable) it would throw an exception.

Upvotes: 1

Related Questions