I'd like a certain function to create a grid and insert a unique object in each slot. The key here is, the function should accept the constructor as a parameter (as there can be multiple constructors that may need to be called via this function), but instantiate multiple objects.
Right now, I have:
//constructor
function NewObj(){
...some stuff
}
//function to construct. Needed since grid function accepts non-constructors as well
function buildNewObj(){ return new NewObj();}
//here is the grid function that takes size and which data to pre-insert as parameters
function newGrid(rows,cols,dataFunction){
var customGrid = [];
for(row=0;row<rows;row++){
var customRow = [];
for(col=0;col<cols;col++){
var data = dataFunction;
customRow.push(data);
}
customGrid.push(customRow);
}
return customGrid;
}
called with:
var myGrid = newGrid(3,3,buildNewObj());
The results of myGrid are a 3x3 grid that all link to the same object. If I place an Alert() within the buildNewObj() function and run this, the alert displays only once.
If we change the code within newGrid to not take the constructor as a parameter, but rather directly reference it like so:
var data = buildNewObj();
instead of
var data = dataFunction;
Then every slot within the grid gets its own unique object.
How can I get a unique object in each slot of the grid while still passing the constructor function via parameter?
Thank you!
Pass the
buildNewObject
as a function, instead of calling it and passing its result.