How to use powerful function composition in Javascript
Function composition is one of the most powerful differentiators between object-oriented and functional approaches to programming in JavaScript.
I will explain the difference between class hierarchy and composed function leading to practical examples of advantages of function composition and functional programming in JavaScript that I use in all of my own code.
Class hierarchy and RoboDog
In object-oriented programming, you define your classes.
For example, you specify a parent class Animal
that has a method move
. You continue by creating classes Cat
and Dog
which will inherit move
from Animal
and add their own methods bark
and meow
.
Then you decide to develop a class Robot
which has a method chargeBattery
.
Now, what if you want to create a class RoboDog
that needs to move
, chargeBattery
and also, do a roboBark
that enhances bark
of your Dog
? You need to inherit from both Dog
and Robot
but JavaScript does not allow you to do that.
To solve these and other issues, it is no longer recommended in object-oriented…