[removed] Passing constructor as parameter, functi

2019-03-03 19:31发布

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!

1条回答
成全新的幸福
2楼-- · 2019-03-03 19:49

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++){
            var data = 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
查看更多
登录 后发表回答