Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:将构造函数作为参数传递,函数只实例化单个对象_Javascript_Oop_Object_Constructor - Fatal编程技术网

Javascript:将构造函数作为参数传递,函数只实例化单个对象

Javascript:将构造函数作为参数传递,函数只实例化单个对象,javascript,oop,object,constructor,Javascript,Oop,Object,Constructor,我想要一个特定的函数来创建一个网格,并在每个插槽中插入一个唯一的对象。这里的关键是,函数应该接受构造函数作为参数(因为可能需要通过该函数调用多个构造函数),但要实例化多个对象 现在,我有: //constructor function NewObj(){ ...some stuff } //function to construct. Needed since grid function accepts non-constructors as well function buildNewObj

我想要一个特定的函数来创建一个网格,并在每个插槽中插入一个唯一的对象。这里的关键是,函数应该接受构造函数作为参数(因为可能需要通过该函数调用多个构造函数),但要实例化多个对象

现在,我有:

//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;
}
myGrid的结果是一个3x3的网格,所有这些网格都链接到同一个对象。如果我在buildNewObj()函数中放置一个警报()并运行它,警报只显示一次

如果我们将newGrid中的代码更改为不将构造函数作为参数,而是直接引用它,如下所示:

var data = buildNewObj();
而不是

var data = dataFunction;
然后网格中的每个插槽都会获得自己的唯一对象

如何在仍然通过参数传递构造函数的情况下,在网格的每个插槽中获得唯一的对象


谢谢大家!

buildNewObject
作为函数传递,而不是调用它并传递其结果

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;
}
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