OOP

Classical inheritance vs Prototypal inheritance?

Class Inheritance:

Instances inherit from classes (like a blueprint — a description of the class)

Create sub-class relationships: hierarchical class taxonomies.

Instances are typically instantiated via constructor functions with the new keyword.

May or may not use the class keyword from ES6.

Prototypal Inheritance:

Instances inherit directly from other objects.

Instances are typically instantiated via factory functions or Object.create().

Instances may be composed from many different objects, allowing for easy selective inheritance.

When is classical inheritance appropriate?

Never, or almost never. Certainly never more than one level. Multi-level class hierarchies are an anti-pattern. I’ve been issuing this challenge for years, and the only answers I’ve ever heard fall into one of several common misconceptions. More frequently, the challenge is met with silence.

Creating is-a relationships.

When is prototypal inheritance appropriate?

There is more than one type of prototypal inheritance:

  • Delegation (i.e., the prototype chain).

  • Concatenative (i.e. mixins, `Object.assign()`)

  • Functional (Not to be confused with functional programming. A function used to create a closure for private state/encapsulation).

Each type of prototypal inheritance has its own set of use-cases, but all of them are equally useful in their ability to enable composition, which creates has-a or uses-a or can-do relationships as opposed to the is-a relationship created with class inheritance.

Composition vs Inheritance

"Favor object composition over class inheritance”

Quote from “Design Patterns: Elements of Reusable Object-Oriented Software”.

It means that code reuse should be achieved by assembling smaller units of functionality into new objects instead of inheriting from classes and creating object taxonomies.

In other words, use can-do, has-a, or uses-a relationships instead of is-a relationships.

Why you might want to create static class members?

Static class members (properties/methods) are not tied to a specific instance of a class and have the same value regardless of which instance is referring to it.

Static properties: typically configuration variables

Static methods: usually pure utility functions which do not depend on the state of the instance.

References

Last updated