DEV Community

Cover image for Prototypes vs Traditional Classes
Natalia
Natalia

Posted on • Updated on

Prototypes vs Traditional Classes

The difference between classes vs prototypes is a common question among Javascript devs and from experience I can say it’s really hard to understand especially if you have only known programming through the lens of JS.

But I think I found a simple way to put this in simple words. Let me know what you think.

I want to start by clarifying that Javascript is a language based on prototypes which is a design pattern. I haven’t read an explanation making this connection before or menting this pattern when clearing up what it’s a prototype, so I thought it was worth meaning it.

If you haven’t heard of design patterns, I recommend you to start checking them out. Basically it’s a standardized pack of solutions for common programming problems. And if you are a Javascript developer definitely take a look at the prototype pattern.

With this pattern you can create a clone of an existing object without being dependent on its class. This may not sound like a big deal for a Javascript developer, but this is not the default behavior in object-oriented languages like Java, in which you can’t create objects out of nowhere by just opening and closing curly brackets; you must create a class to be able to create an object.

You can always implement a prototype design in Java, but the entire language wasn’t built upon it.

So we fall back into the question, what’s the difference between traditional classes (like the ones you found in languages like Java) and the prototypes you found in Javascript?

As a Javascript developer myself, I came up with this analogy to help my brain solidify the idea:

With prototypes you are creating clones, with traditional classes you are given birth.

The cloned objects are also able to clone themself, so the design is not based on creating a blueprint responsible for constructing objects, but in objects able to copy and paste themself.

With the arrival of “classes” in Javascript, this concept was harder to understand, they look like classes, so they must be classes right?....well not quite the case, they are just a different way to write prototype objects, underneath they are nothing like the traditional classes.

Let me know what you think, is this a good way to explain the difference?

Discussion (0)