DEV Community

Discussion on: How is JavaScript class / prototype different from Python / Java?

Collapse
 
chrispardy profile image
chris-pardy

First to address TypeScript, there is no difference between TypeScript and JavaScript as far as classes are concerned. TypeScript supports "private" fields on classes, but it's more a suggestion (like the underscore prefix) than something enforced. In general the advantage of enforcing private fields, meaning that the field cannot be read or written to, is that you can rely on that field only changing in ways that your class specifies.

To understand the difference between class based and prototype based inheritance it's best to think of how we resolve a field/method.

In class based inheritance an object has fields that are specific to that instance and a class, the class has every field/method that is shared by all instances of this class. This includes all the fields on the classes parent class and the parent's class parent class etc. It's possible to do this because classes declare their parent classes, and those declarations don't change. Now to resolve a field on an object we first check the object, then the class, then we're done.

In prototype based inheritance an object has fields that are specific to that instance and a prototype, which is an object. Because a prototype is an object it has fields and a prototype. To resolve a field you first check if it's defined in the object, then check if it's defined in the prototype, then check the prototype's prototype, etc.

Given the nature of prototype inheritance it's potentially much slower than class based inheritance, however you get a trade-off in flexibility. For instance switching the prototype of an object after it's been created is trivial in JavaScript and effectively impossible in Java. You can also make changes arbitrarily in the prototype chain, which is powerful but also scary.

One note is that the ES6 classes have a syntax that makes then look a lot like classes in Java or Python but they are not. It's just a new syntax over the old functionality.

Not going to go into mixins, as others have explained they're a way to inherit from 2 different classes, how they're implemented is largely language specific.