Steve Yegge recently posted an interesting blog post on what he calls the universal design pattern. In there he details using prototypes as a modelling tool, instead of classes. I like the way this introduces less coupling compared to inheritance. But that is something one can get with classes as well, by implementing classes in terms of other classes, instead of inheritance. Does anyone else have success stories of using prototypes, and can maybe help explain where using prototypes is advantageous compared to classes. I guess it comes down to static modelling versus dynamic modelling, but more examples would be very welcome.
Prototypes vs. Classes. The most important difference between class- and prototype-based inheritance is that a class defines a type which can be instantiated at runtime, whereas a prototype is itself an object instance.
Prototype-based programming is a style of object-oriented programming in which behaviour reuse (known as inheritance) is performed via a process of reusing existing objects that serve as prototypes. This model can also be known as prototypal, prototype-oriented, classless, or instance-based programming.
JavaScript uses prototypes instead of classes for inheritance. It is possible to simulate many class-based features with prototypes in JavaScript.
Again, prototype is just a property that every function in JavaScript has and, as we saw above, it allows us to share methods across all instances of a function.
One interesting bit is that it's easy to make a prototype-based language act OO but it's difficult to make an OO language act prototype-based.
It's not entirely clear what OO as prototype would look like, aside from composition versus inheritance as you mention.
A prototype language makes complex inheritance behavior easy. You can implement multiple inheritance, mixin-like behavior, or just pick and choose what you want from one object to add to another.
Wikipedia's article mentions: "Advocates of prototype-based programming often argue that class-based languages encourage a model of development that focuses first on the taxonomy and relationships between classes. In contrast, prototype-based programming is seen as encouraging the programmer to focus on the behavior of some set of examples and only later worry about classifying these objects into archetypal objects that are later used in a fashion similar to classes."
That's not to say the prototype paradigm is all pros and no cons. If OO is more restrictive, it's because it chooses to be. I can see where all that flexibility might get you into trouble if you aren't careful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With