Skip to content Skip to sidebar Skip to footer

Javascript: Passing Constructor As Parameter, Function Instantiates Only A Single Object

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 mu

Solution 1:

Pass the buildNewObject as a function, instead of calling it and passing its result.

function newGrid(rows,cols,dataFunction) {
    var customGrid = [];
    for (var row=0;row<rows;row++){
        var customRow = [];
        for (var col=0;col<cols;col++){
            vardata = dataFunction(); // yes, it's a function// we need (want) to call it
            customRow.push(data);
        }
        customGrid.push(customRow);
    }
    return customGrid;
}

var myGrid = newGrid(3,3,buildNewObj); //no parenthesis, no invocation

Post a Comment for "Javascript: Passing Constructor As Parameter, Function Instantiates Only A Single Object"