Last active
November 10, 2021 15:16
-
-
Save theScottyJam/1e1689f73c557163f4dc84838fa5511e to your computer and use it in GitHub Desktop.
Article: Composition Alone Can't Replace Inheritance - restricted inheritance
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
const monsterHelpers = { | |
attack() { | |
playHurtAnimation() | |
} | |
} | |
class MonsterBehaviors { | |
#id = Math.random() | |
#dropLoot | |
constructor({ dropLoot }) { | |
if (this.constructor === MonsterBehaviors) { | |
throw new Error('This is an abstract class. Do not instantiate it directly.'); | |
} | |
this.#dropLoot = dropLoot | |
} | |
die() { | |
userInventory.add(this.#dropLoot()) | |
removeFromUi(this.#id) | |
} | |
// Other shared functions could be defined here as well. | |
} | |
export class Slime extends MonsterBehaviors { ... } | |
export class Skeleton extends MonsterBehaviors { ... } | |
export class Clown extends MonsterBehaviors { | |
constructor() { | |
super({ | |
dropLoot: () => this.dropLoot() | |
}) | |
} | |
dropLoot() { | |
return [new Key()] | |
} | |
attack() { | |
monsterHelpers.attack() | |
if (itsTime()) { | |
showCutScene() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment