Skip to content

Instantly share code, notes, and snippets.

@caderek
Last active November 23, 2021 01:35
Show Gist options
  • Select an option

  • Save caderek/fbdfa41bbfc33cbf3424708923b2f0f3 to your computer and use it in GitHub Desktop.

Select an option

Save caderek/fbdfa41bbfc33cbf3424708923b2f0f3 to your computer and use it in GitHub Desktop.
Object composition - class part 2
class Swimmable {
constructor() {
this.speed = 1
}
swim() {
console.log(`Swam ${this.speed} meter(s)`)
}
}
class Quackable {
constructor() {
this.speed = 1
}
quack() {
console.log("Quack!".repeat(this.speed))
}
}
// Without DI
class Duck {
#swimmable
#quackable
constructor() {
this.#swimmable = new Swimmable()
this.#quackable = new Quackable()
this.#swimmable.speed = 2
this.#quackable.speed = 3
}
swim() {
this.#swimmable.swim()
}
quack() {
this.#quackable.quack()
}
}
const donald = new Duck()
donald.swim() // Swam 2 meter(s)
donald.quack() // Quack!Quack!Quack!
// With DI
class Duck2 {
#swimmable
#quackable
constructor(swimmable, quackable) {
this.#swimmable = swimmable
this.#quackable = quackable
this.#swimmable.speed = 2
this.#quackable.speed = 3
}
swim() {
this.#swimmable.swim()
}
quack() {
this.#quackable.quack()
}
}
const swimmable = new Swimmable()
const quackable = new Quackable()
const donald2 = new Duck2(swimmable, quackable)
donald2.swim() // Swam 2 meter(s)
donald2.quack() // Quack!Quack!Quack!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment