Skip to main content

Command Palette

Search for a command to run...

Class-based? Prototype-based? Why?

Key differences between object-oriented programming languages

Published
โ€ข2 min readโ€ขView as Markdown
Class-based? Prototype-based? Why?
D

I'm a mixtape of data scientist, software developer, and mechanical engineer. I nerd out on learning new things and dabbling in new domains.

I like trails, ultramarathons, and sourdough baking. ๐Ÿ”๐Ÿƒ๐Ÿฅ–

While learning Python or JavaScript you are likely to come across the concept of class-based (Python) versus prototype-based (JavaScript) languages. Both are object-oriented language, so why the distinction?

Class-based language (Python)

At the root of class-based languages are classes and instances. A class is a blueprint that defines all the properties and methods for a specific set of objects. Classes can have hierarchies where subclasses inherit properties or methods from superclasses. For example, an "apple" class would inherit from a "fruit" class (also common to say that the "fruit" class is extended by the "apple" class). Lastly to create an object, it must be explicitly created based on a class and is then considered to be an instance of that class.

Prototype-based language (JavaScript)

A prototype-based language does not use classes to define objects. Instead, objects are objects. Any object can specify its own properties and it can also inherit directly from other objects through a prototype property. An "apple" object is cloned from the "fruit" object and properties specific to apples can then added.

Constructors

Defining a class in a class-based language is done through a class definition. Within that definition you specify special constructor methods (like __init__() in Python) to define initial property values or other functionalities and whether the new class is a subclass of another class.

Prototype-based languages follow a similar approach, but do not distinguish class definition from the constructor. Instead, the constructor function definition handles everything by creating objects with initial property values. A prototypical object can also be defined within the constructor function to specify which object the new object should inherit from.