Skip to content

Instantly share code, notes, and snippets.

@ticking-clock
Last active November 19, 2015 21:02
Show Gist options
  • Save ticking-clock/d843d5871ec1e839bf10 to your computer and use it in GitHub Desktop.
Save ticking-clock/d843d5871ec1e839bf10 to your computer and use it in GitHub Desktop.
OOP in JS, Part 2: Attack of the Frameworks

Objective

Create a simple "class" in Javascript, using various frameworks and pre-processors.

The Class

Let's build a "player" object for a game. This player will have properties like:

  • Health
  • Level
  • Experience
  • Attributes
  • Inventory

And it will have instance methods, like:

  • damage(amount)
  • gainExperience(amount)

As well as static methods, like:

  • inSameParty(player1, player2)

The Frameworks and Pre-processors

  1. ES6
  2. Coffeescript
  3. AngularJs
  4. EmberJs
  5. BackboneJs
class Player
constructor: (@health = 10) ->
@attributes =
str: 8, int: 8, wis: 8,
dex: 8, con: 8, cha: 8
damage: (amount) ->
@health += amount
@inSameParty: (p1, p2) ->
false
p1 = new Player 20
console.log p1.health
class MagicUser extends Player
constructor: (health, @mana = 0) ->
super health
class Player {
constructor(health = 10) {
this.health = health;
this.attributes = {
str: 8, int: 8, wis: 8,
dex: 8, con: 8, cha: 8
};
}
damage(amount) {
this.health -= amount;
this.healthcheck();
}
// Through the magic of Object.defineProperty
get health() {
return this.health;
}
set health(amount) {
this.health = amount;
}
static inSameParty(p1, p2) {
return false;
}
}
let p1 = new Player(20);
console.log(p1.health);
class MagicUser extends Player {
constructor(health, mana = 0) {
super(health);
this.mana = mana;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment