What is a class, anyway?

We in the JavaScript community tend to have a very narrow view of what a class is and of what classical inheritance can do. We tend to think that classical inheritance can only be a compile-time, single-parent relationship. But what if I told you that classes and classical inheritance are much more versatile than you may have thought?

  • A class can be either a compile-time concept (such as in Java or C#) or a class can be a run-time object (such as in Python or Smalltalk).
  • The inheritance process can happen either at compile-time (such as in Java or C++) or the inheritance process can happen at run-time (such as in Python or JavaScript).
  • A descendant can either be limited to inherit from just one parent (such as in C# or JavaScript) or a descendant may be allowed to inherit from any number of parents (such as in C++ or Python).

So what, then, ties it all together? What is a class? What is inheritance? (From the UML manual) A class is the description of both the data structure and the behavior that is shared among a set of objects. And inheritance is the process of incorporating structure and behavior.

Consider this Python code:

class B():
def b(self):
return "b"
class D(B):
def d(self):
return "d"
instance = D()
instance.b() # "b"
instance.d() # "d"

Are these classes? Is this classical inheritance?

What if I told you that class B and class D are themselves runtime objects? What if I told you that when we access instance.b, Python looks for the name “b” on the instance object, and if it doesn’t find it, then it looks for it on the “D” object, and if it still doesn’t find it, it looks on the “B” object, and so on down the inheritance chain.

Does that process sound familiar?

Next, consider these JavaScript factory functions:

function b() {
return {
b: function () {
return 'b';
},
};
}
function d() {
return Object.assign(b(), {
d: function () {
return 'd';
},
});
}
var o = d()
o.b(); // "b"
o.d(); // "d"

We may be reluctant to call these classes or classical inheritance, but here’s what we can certainly say:

“d” defines a structure and behavior that is common to a set of objects, and it incorporates the structure and behavior of “b”, which itself defines a structure and behavior that is common to a set of objects.

Like what you read? Give Jeff M a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.