Skip to content

Instantly share code, notes, and snippets.

@codeincontext
Created May 22, 2012 23:14
Show Gist options
  • Save codeincontext/2772254 to your computer and use it in GitHub Desktop.
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)
// 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