Skip to content

Instantly share code, notes, and snippets.

@JimOKelly
Created July 24, 2016 16:04
Show Gist options
  • Save JimOKelly/5cecc6ac6d26334500cf87082b9d95f6 to your computer and use it in GitHub Desktop.
Save JimOKelly/5cecc6ac6d26334500cf87082b9d95f6 to your computer and use it in GitHub Desktop.
A way to 'decorate' your objects in JavaScript
var Adventurer = function(options) {
this.name = options.name;
this.gender = options.gender;
this.class = options.class;
this.race = options.race;
this.position = options.position || 'standing';
this.effects = [];
this.hits = [];
this.attributes = {};
this.status = {};
return this;
};
var addPositional = function(adventurer) {
adventurer.sleep = function() {
adventurer.position = 'sleep';
};
adventurer.sit = function() {
adventurer.position = 'sit';
};
adventurer.stand = function() {
adventurer.position = 'stand';
};
};
var addWarriorSkills = function(adventurer) {
adventurer.bash = function(target) {
target.hits.push({type: 'bash', damage: 25});
};
};
var addMageSkills = function(adventurer) {
adventurer.castSleep = function(target) {
target.sleep();
};
adventurer.cast = function(spell, target) {
var capitalize = function(word) {
return word[0].toUpperCase() + word.slice(1, word.length);
};
var spellName = function(spell) {
return [
'cast',
capitalize(spell)
].join('');
};
adventurer[spellName(spell)](target);
};
};
var timmy = new Adventurer({
name: "Timmy the Terrible",
gender: 'male',
class: 'warrior',
race: 'minotaur',
effects: [],
position: 'standing',
attributes: {
strength: 18,
intelligence: 8,
wisdom: 8,
charisma: 8,
dexterity: 16
},
status: {
health: 100,
mana: 0,
move: 100
},
});
var allie = new Adventurer({
name: "Allie the Awful",
gender: 'female',
class: 'mage',
race: 'elf',
effects: [],
position: 'standing',
attributes: {
strength: 8,
intelligence: 17,
wisdom: 12,
charisma: 8,
dexterity: 12
},
status: {
health: 100,
mana: 120,
move: 100
},
});
addWarriorSkills(timmy);
addPositional(timmy);
addMageSkills(allie);
addPositional(allie);
timmy.bash(allie);
allie.cast('sleep', timmy);
console.log(timmy);
console.log(allie);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment