Last active
November 23, 2021 01:35
-
-
Save caderek/fbdfa41bbfc33cbf3424708923b2f0f3 to your computer and use it in GitHub Desktop.
Object composition - class part 2
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
| 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