Created
April 8, 2012 00:02
-
-
Save rwaldron/2333015 to your computer and use it in GitHub Desktop.
ES Monsters
This file contains hidden or 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
| // A private name used by the Monster class | |
| const pHealth = Name.create(); | |
| class Monster { | |
| // A method named "new" defines the class’s constructor function. | |
| new(name, health) { | |
| this.name = name; | |
| this[pHealth] = health; | |
| } | |
| // An identifier followed by an argument list and body defines a | |
| // method. A “method” here is simply a function property on some | |
| // object. | |
| attack(target) { | |
| log('The monster attacks ' + target); | |
| } | |
| // The contextual keyword "get" followed by an identifier and | |
| // a curly body defines a getter in the same way that "get" | |
| // defines one in an object literal. | |
| get isAlive() { | |
| return this[pHealth] > 0; | |
| } | |
| // Likewise, "set" can be used to define setters. | |
| set health(value) { | |
| if (value < 0) { | |
| throw new Error('Health must be non-negative.') | |
| } | |
| this[pHealth] = value | |
| } | |
| // We can create arbitrary properties on the prototype by | |
| // using the prototype keyword | |
| prototype { | |
| numAttacks: 0, | |
| attackMessage: 'The monster hits you!' | |
| } | |
| // Class properties can be added using a static property initializer | |
| static { | |
| allMonsters: [] | |
| } | |
| // Class methods can be added using the static method modifier | |
| static numMonsters() { | |
| return this.allMonsters.length; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment