What are advantages and disadvantages of prototypal OOP?

Prototype-based programming is a style of object-oriented programming in which inheritance is implemented via process of cloning existing objects that serve as prototypes. Read more about prototype-based OOP here. Class-based inheritance enables new classes to take on the properties and behavior of existing classes.

What are advantages of prototypal inheritance?

  • It is more trivial to create new "classes".
  • Instances can become templates for other instances, if you want to "clone" an object, just use the existing object as the prototype for the new object. No need to write lots of complex cloning logic for different classes.
  • Multiple inheritance is easier - you just copy a subset of the properties from one prototype and paste them to another prototype.
  • It is quite easy to change behavior at run time - you can just change properties, hence "morph" an object to another shape dynamically.
  • "Classes" are usually smaller in terms of code lines.

What are disadvantages?

  • Some performance overhead - since when you access property you are forced to go through chain of prototypes till you find requested one.
  • You lose benefits of static typing - you are working with a dynamic object system. This means that you usually need to write more unit tests to ensure behavior is correct.
  • Refactoring might be more difficult, since you build your own inheritance hierarchy with code. IDE/refactoring tool can't really help you since they can't understand your approach. You probably want unit tests to check that your inheritance hierarchy is being constructed correctly before doing refactoring.
  • It might be confusing for people used to class-based OOP. Prototype based OOP is less spread than classical.

Short answer

  • Prototype-based programming is a style of OOP when inheritance is implemented via process of cloning existing objects.
  • In class-based OOP inheritance is built around "parent-child" relationship between classes.
  • There are advantages and disadvantages between this two approaches, so consider what suits your needs carefully.

Comments