DEV Community

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

Collapse
 
rhymes profile image
rhymes

Not sure I can touch on all the topics, going to ignore Typescript because I don't know it.

JS is an OOP language with prototype based inheritance which essentially means that the template to create a new object is another object. @lydiahallie wrote a great visual explanation on how that works: JavaScript Visualized: Prototypal Inheritance.

Java and Python also are object oriented but they implement a different paradigm, class based inheritance, which essentially means objects are printed from a class which acts as their template. Class based inheritance allows multiple inheritance, which Python offers.

Mixins are a good way to share behavior between objects, they could be viewed as a way to bypass the limitations of single class inheritance.

Not to say that multiple inheritance is the perfect solution, it can get complicated fast. The more I program the more I prefer to keep classes simple and rely on composition and dependency injection to create objects with the various bits of shared behavior.

Not everyone agrees, Ruby has mixins that in a real world app can quickly become similar to the issues that multiple inheritance has, the simplest being: "where does this method call I'm seeing in this line come from?". The same can happen with open classes. JS has a similar potential behavior with the fact that you can add methods to objects or their prototype at runtime.

None of this is inherently a problem, it's quite a perk of these dynamic languages, it becomes an issue if devs don't have a bit of "discipline" in how they extend behavior.

And with this we circle back to your other concern, encapsulation. My belief is that essentially Python is built with an unspoken contract in which the creator of the class trusts the consumer of the class because they are "both adults" and if the latter wants to delve into the private methods or private state it's their own responsibility.

So Python trusts devs, Java is on the opposite side of the spectrum in this. The agreement is that the consumer of the class shall always stick with the public interface of the class. The only drawback, which happened to me in the past, is that if the implementor made a mistake in the design of the class, the consumer essentially has to wait until the new version is available, whereas with Python you write code to bypass the mistake and wait for the new version to remove the patch.

Hope this was helpful to understand the different philosophies.