问题描述
我想要一个函数来创建一个网格,并在每个插槽中插入一个唯一的对象。这里的关键是,函数应该接受构造函数作为参数(因为可能有多个构造函数可能需要通过此函数调用),但实例化多个对象。
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.
现在,我有:
//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;
}
调用方式:
var myGrid = newGrid(3,3,buildNewObj());
myGrid的结果是一个3x3网格,它们都链接到同一个对象。如果我在buildNewObj()函数中放置一个Alert()并运行它,则警报只显示一次。
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.
如果我们更改newGrid中的代码,作为参数,而是直接引用它,像这样:
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();
而不是
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?
谢谢!
推荐答案
将 buildNewObject
作为函数传递,而不是调用它并传递结果。
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
这篇关于Javascript:传递构造函数作为参数,函数仅实例化一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!