HTML and CSS Reference
In-Depth Information
Refactoring PlayerMissile
The PlayerMissile object was already compact, but refactoring helps make it even shorter. See Listing 2-6 .
Listing 2-6: Refactored PlayerMissile
var PlayerMissile = function(x,y) {
this.setup('missile',{ vy: -700 });
this.x = x - this.w/2;
this.y = y - this.h;
};
PlayerMissile.prototype = new Sprite();
PlayerMissile.prototype.step = function(dt) {
this.y += this.vy * dt;
if(this.y < -this.h) { this.board.remove(this); }
};
The constructor method still needs to explicitly set the x and y location because these are dependent on the
width and height of the sprite (which aren't available until after setup is called). The step method is unaf-
fected by the refactoring, and the draw method can be removed as it's handled by Sprite .
Refactoring Enemy
The Enemy object benefits the most from the refactoring, particularly in the constructor method. Instead of us-
ing a number of loops to copy parameters into the object, a few calls to merge simplify the method down to
three lines. See Listing 2-7 .
Listing 2-7: Refactored Enemy Object (Partial Code)
var Enemy = function(blueprint,override) {
this.merge(this.baseParameters);
this.setup(blueprint.sprite,blueprint);
this.merge(override);
}
Enemy.prototype = new Sprite();
Enemy.prototype.baseParameters = { A: 0, B: 0, C: 0, D: 0,
E: 0, F: 0, G: 0, H: 0,
t: 0 };
The step method is unaffected (and so isn't shown in Listing 2-7 ) and the draw method can be removed.
Notice that merge is called explicitly to merge in the set of baseParameters and the override paramet-
ers. The predefined baseParameters object is also pulled out of the constructor and put into the prototype.
Although not a huge optimization, it prevents the need for the static baseParameters object to be re-created
each time a new Enemy is created just for the sake of being copied over into the object. Because basePara-
meters isn't going to be modified, one copy of the object will do.
 
 
 
 
Search WWH ::




Custom Search