Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.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 - Fatal编程技术网

如何生成多个对象?(JavaScript)

如何生成多个对象?(JavaScript),javascript,Javascript,我有多个这样的对象(16) 从该对象继承所有 function MobRoot(x,y,size,speed,target,sps,life) { this.size = size*WindowScale; this.x = x; this.y = y; this.angle = 0; this.speed=speed; this.colided=false; this.maxlife = life; this.life = li

我有多个这样的对象(16)

从该对象继承所有

function MobRoot(x,y,size,speed,target,sps,life) 
{
    this.size = size*WindowScale;
    this.x = x;
    this.y = y;
    this.angle = 0;
    this.speed=speed;
    this.colided=false;
    this.maxlife = life;
    this.life = life;
    this.buffArray = [];
    this.sps = sps;
    this.target = target;
    this.direction = 
    {
        x:0,
        y:0
    }
    //x,y,w,h
    //ex sprite[0][0] = 0,0,500,500;
    this.spsCoord = [];
    this.isBoss = false;
}
MobRoot.prototype.directionUpdate = function()
{
this.direction.x = this.speed*Math.cos(this.angle)*-1;
this.direction.y = this.speed*Math.sin(this.angle)*-1;
}
    /*aditional methods for mobRoot*/
我想从一个数组中生成不同的怪物。目前,我正在为每种类型分配一个数字(例如:1-Baboo 2-Spider 3-which),并将这些数字存储在数组中,当我生成它们时,我对数组中的每个mobIndex使用一个开关,如下所示

switch(wave[i])
{

    case 1:
        mobs.push(new Baboo(arg1,arg2,...));
        break;

    case 2: 
        mobs.push(new Spider(arg1,arg2,...));
        break;

    /*...*/

    case 999: 
    mobs.push(new Whatever(arg1,arg2,...));
    break;
}

有没有更优雅的方法来解决此类问题?

您可以将所有构造函数放入一个数组中:

var constructors = [Baboo, Spider, Whatever, ...];
if (wave[i] < constructors.length) {
    mobs.push(new constructors[wave[i]](arg1, arg2, arg3, ...));
}
var构造函数=[Baboo,Spider,随便什么,…];
if(波[i]
每次创建一个新的
Baboo
,您都在替换
Baboo.prototype
,因此您丢失了加载脚本时分配的所有原型函数。好的,所以我需要
Baboo.prototype=Object.create(MobRoot.prototype)在构造函数之外@巴尔马耶斯。它应该只做一次,就像所有其他原型设置一样。好的,关于生成每个对象的方法,有没有比使用switch更好的方法@巴尔马
var constructors = [Baboo, Spider, Whatever, ...];
if (wave[i] < constructors.length) {
    mobs.push(new constructors[wave[i]](arg1, arg2, arg3, ...));
}