Skip to content

Instantly share code, notes, and snippets.

@theScottyJam
Last active November 10, 2021 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theScottyJam/1e1689f73c557163f4dc84838fa5511e to your computer and use it in GitHub Desktop.
Save theScottyJam/1e1689f73c557163f4dc84838fa5511e to your computer and use it in GitHub Desktop.
Article: Composition Alone Can't Replace Inheritance - restricted inheritance
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