Before the ‘class’ keyword

Here is an exemple of how we implemented ‘classes’ in Javascript not so long ago. The first function would be kind of a constructor, so we have a Cat class and we have a function in this class that will meow :

You create cat with the keyword new

Quicknote : what if you forget the new keyword ? Well it doesn’t throw any error … and you just renamed your window.

It’s all about what this is referring to

Where is the prototype

In the console you can clearly see the prototypal chain:

Here’s what your cat contains

Your cat is an object with a name, it has an object __proto__ that contains a function meow and the Cat constructor, this object/prototype also contains an object Object (which is the base object, kind of like Java, that is the base prototype of all javascript objects). You can see why it is called a prototypal chain.

Now one of the things that differs a lot from how it would work with ‘classical’ classes is that prototypes are references. Which means that if you create a lot of cats and do that on one of them

delete cat.__proto__.meow

You just removed the capacity to meow to all your cats, because they all share the same reference to the Cat prototype.