Created
May 22, 2012 23:14
-
-
Save codeincontext/2772254 to your computer and use it in GitHub Desktop.
Toying with this pattern for complex JS objects (replicating 'class' and 'instance' methods/variables)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Constants | |
Solar = { | |
START_HEALTH: 100, | |
RADIUS: 10, | |
COLOR: "FF0", | |
RECYCLE: 50, | |
RANGE: 50, | |
ENERGY_PRODUCED: 0.5, | |
STORAGE: 25, | |
COST: 200, | |
RADIUS: 10, | |
SELECTED_COLOR: "880" | |
} | |
// Constructor for each instance | |
Solar.instance = function(x, y) { | |
this.type = Solar; | |
this.x = x; | |
this.y = y; | |
this.health = Solar.START_HEALTH; | |
lex.maxEnergy += Solar.STORAGE; | |
} | |
// Methods for each instance | |
Solar.instance.prototype.tick = function() { | |
var a = lex.energy + this.ENERGY_PRODUCED; | |
if (a > lex.maxEnergy) { | |
lex.energy = lex.maxEnergy; | |
} | |
else { | |
lex.energy = a; | |
} | |
}; | |
Solar.instance.prototype.drawOnContext = function(context) { | |
context.beginPath(); | |
context.fillStyle=Solar.COLOR; | |
context.arc(this.x,this.y,Solar.RADIUS,0,Math.PI*2,true); | |
context.strokeStyle = "#000"; | |
context.stroke(); | |
context.closePath(); | |
context.fill(); | |
} | |
// Usage | |
baseStation = new Solar.instance(250, 250); | |
solarColor = Solar.COLOR; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment