2017-01-01 95 views
0

我有這樣的(16)如何生成多個對象?(JavaScript的)

function Baboo(x,y,size,speed,target,sps,life){ 
    MobRoot.call(this,x,y,size,speed,target,sps,life); 
    this.spsCoord = [500*0,500*3,500,500]; 
    this.coolDown = 60; 
    this.atack = 0;} 
    Baboo.prototype = Object.create(MobRoot.prototype); 

Baboo.prototype.throw = function() 
{ 
    projectiles.push(new Arrow(this.x,this.y,10,10,this.angle,150,this.target)); 
} 
Baboo.prototype.update = function(){ 
if(this.life>0) 
{ 
    this.sendBack(); 
    this.draw(); 
    this.checkClick(); 
    this.angle = CalculateSlope(this,this.target); 
    this.directionUpdate(); 
    this.updateBuffs(); 
    this.x += this.direction.x; 
    this.y += this.direction.y; 
}} 
    /*etc aditional methods*/ 

,從這個對象

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-Whatever)並將這些數字存儲在數組中,當我生成它們時,我使用一個開關來爲數組中的每個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; 
} 

有沒有更好的解決這類問題的方法?

+2

每次你創建一個新的'Baboo',您要更換'Baboo.prototype',讓你失去了你分配的所有功能樣機當你加載腳本。 – Barmar

+0

好的,所以我需要'Baboo.prototype = Object.create(MobRoot.prototype);'在構造函數之外? @Barmar –

+0

是的。它應該只做一次,就像所有其他原型設置一樣。 – Barmar

回答

0

你可以把所有構造函數到一個數組:

var constructors = [Baboo, Spider, Whatever, ...]; 
if (wave[i] < constructors.length) { 
    mobs.push(new constructors[wave[i]](arg1, arg2, arg3, ...)); 
} 
+0

非常感謝! –