Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.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 如何在js中传递参数来创建变量?_Javascript_Function_Class_Parameters - Fatal编程技术网

Javascript 如何在js中传递参数来创建变量?

Javascript 如何在js中传递参数来创建变量?,javascript,function,class,parameters,Javascript,Function,Class,Parameters,我正在尝试使用javascript、类和threejs来创建一个项目。我有一个想法,让一个单一的函数创建一个新的threejs对象,但不知道如何实现它 让我说得更详细一点。我有一个使用threejs创建多维数据集的类: class Cube { constructor(geometry, material, /*position variables*/, scene) { this.geometry = geometry; this.material = material;

我正在尝试使用javascript、类和threejs来创建一个项目。我有一个想法,让一个单一的函数创建一个新的threejs对象,但不知道如何实现它

让我说得更详细一点。我有一个使用threejs创建多维数据集的类:

class Cube {
  constructor(geometry, material, /*position variables*/, scene) {
    this.geometry = geometry;
    this.material = material;
    /* this.positions */
  }
  createMesh() {
    //creates a mesh for the cube
    this.mesh = new THREE.Mesh( this.geometry, this.materials );
  }
  addToScene() {
      this.scene.add( this.mesh );

      /* changes position with variables */
  }

}
这个类工作得很好,但我想创建一个新函数,该函数生成一个唯一的多维数据集,并带有一个自定义变量我想创建如下内容:

var createCube = function ( name, geometry, material, /*position*/, scene) {
    name = new Cube(geometry, material, /*position*/, scene;
}
然后,在使用此函数后,我可以使用参数中的名称,如下所示:

createCube( customName, cubeGeometry, cubeMaterial, /*position*/, threeScene);
customName.createMesh();
customName.addToScene();
我意识到我总是可以硬编码多维数据集的名称,但是,我将通过循环来创建多个多维数据集。
对于一个可能的简单解决方案,我给出了很多解释,但我希望这有助于说明我正在尝试做什么。如果你需要更多的解释,我愿意这样做

您不能这样做,JS不允许将引用作为方法参数传递。 我不清楚您最终想要实现什么,下面是我在
cubeObject
上定制命名立方体的尝试

const cubesObject = {};
for (const name of ['a', 'b', 'c']) {
  cubesObject[name] = new Cube(geometry, material, /* position */, scene);
}
console.log(cubesObject.a, cubesObject.b, cubesObject.c)

我不完全确定我是否理解这里的问题。我可能错过了什么

如果一个
多维数据集
需要由
名称
标识,您可以将其添加为
多维数据集
的属性吗

类多维数据集{
构造函数(名称,/*其他属性*/){
this.name=名称;
/*其他属性*/
}
createMesh(){
}
addToScene(){
}
}
常量名称=['cube1','cube2','cube3'];
const cubes=names.map(name=>新立方体(名称、几何体、材质、/*位置*/、场景));
forEach(cube=>{
log(`cube:${cube.name}`);
createMesh();
cube.addToScene();
});

动态执行此操作的更好方法是创建一个数组并将对象推送到该数组中。在使用节点应用程序时,我得到了类似的输出

var cubesArray=[]
函数createCube(名称、几何体、材质、/*位置*/、场景){
让thisCube=新立方体(几何体、材质、/*位置*/、场景);
立方体阵列[名称]=此立方体;
}

现在,我们可以使用:cubesArray[name].property或cubesArray[name].function()执行所有函数并访问属性。如果需要创建多个,请将它们全部放在一个数组中。我的意思是通过for循环来创建多个,而对于我正在做的事情,数组的效率就没有那么高了。数组或对象都是保存动态创建对象的方式。你真的应该
返回新的多维数据集值,然后使用
const customName=createCube(cubegemetry,cubeMaterial,/*position*/,threeScene)。请向我们展示您遇到问题的循环。这也是一种更好的方法来完成我需要做的事情!谢谢