Replace Classes with Higher Order Functions

An OOPs Class is simply a Template for Creating Objects, that encapsulate Data and Behavior.

In Functional Paradigm, the same encapsulation of Data and Behavior can be achieved using a Higher Order Function (HOF) that replaces the OOPs Class. This HOF, would get the Data from outside (to keep it pure) and will return a function (Behavior) that uses Closure to encapsulate the Data within the returned function.

In JavaScript, any function can instantiate and return objects. When you do so without a constructor, it’s called a factory function`class` can’t compete with the power and flexibility of factories — specifically stamps, and object pools are not the only factory use-case.

There is a whole section on object construction in the GoF “Design Patterns” book which exists only to get around the limitations of constructors and classes.

See also: Three Different Kinds of Prototypal OO.

The bottom line: Class doesn’t give you any power that isn’t already supplied by factory functions and the prototypal OO built into the language. All you’re doing when you create a class is opting into a less powerfull, less flexible mechanism and a whole lot of pitfalls and pain.

ref: https://medium.com/javascript-scene/how-to-fix-the-es6-class-keyword-2d42bb3f4caf

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s