I coded an application that isn't entirely OOP. I was considering converting it to "real" OOP.
Right now, the code is structured by setting subfunctions as attributes to main functions.
Ex: Bullet.move.normal
is a subfunction/dependency or Bullet.move
.
This is how the code looks right now:
Bullet = function(x,y,angle,type){
return {x:x,y:y,angle:angle,type:type};
}
Bullet.update = function(b){
Bullet.move(b);
Bullet.collision(b);
}
Bullet.move = function(b){
if(b.type === 'normal') Bullet.move.normal(b);
else if(b.type === 'sinus') Bullet.move.sinus(b);
}
Bullet.move.normal = function(b){
b.x += Math.cos(b.angle); b.y += Math.sin(b.angle); //not important
}
Bullet.move.sinus = function(b){
b.x += Math.cos(b.x); b.y += Math.sin(b.y); //not important
}
Bullet.collision = function(b){
Bullet.collision.wall(b);
Bullet.collision.actor(b);
}
Bullet.collision.wall = function(b){}
Bullet.collision.actor = function(b){}
---
I've started to write the OOP version of the code above but the structure I had doesn't work perfectly.
this
parameter doesn't refer to the object if it's a "multilevel" function. (Check Bullet.prototype.move.normal
)
What would be the recommended way to restructured the prototype without having to put all subfunctions in the main function? (Check 2nd Bullet.prototype.move
)
Is there a solution other than just naming everything like Bullet.prototype.move_normal
? I'd prefer to not have everything on the same "level".
And what would be the advantages of using OOP instead of what I had before? Is it worth converting to OOP?
Bullet = function(x,y,angle,type){
this.x = x;
this.y = y;
this.angle = angle;
this.type = type;
}
Bullet.prototype.update = function(){
this.move();
this.collision();
}
Bullet.prototype.move = function(){
if(this.type === 'normal') this.move.normal();
else if(this.type === 'sinus') this.move.sinus();
}
Bullet.prototype.move.normal = function(){
//not working, this === Bullet.prototype.move, not the bullet
this.x += Math.cos(this.angle); //not important
this.y += Math.sin(this.angle);
}
Bullet.prototype.move = function(){ //I dont want this. I'd like to keep things separated.
if(this.type === 'normal'){
this.x += Math.cos(this.angle);
this.y += Math.sin(this.angle);
}
else if(this.type === 'sinus'){
this.x += Math.cos(this.x);
this.y += Math.sin(this.y);
}
}