Benefits of prototypal inheritance over classical
javascript - Benefits of prototypal inheritance over classical? - Stack OverflowJavaScript has prototypal inheritance as opposed to classical inheritance in for example Java
It's basically just objects delegating tasks to other objects.
- Create a brand new object (
var foo = {}
) - Clone this object and extend it. The cloned object will delegate to its prototype (
foo
).var bar = Object.create(foo)
The advantages of prototypal inheritance
The pattern is simple
(see the first two steps above). As opposed to in classical inheritance:
- Classes
- Object
- Interfaces
- Abstract Classes
- Final Classes
- Virtual Base Classes
- Constructors
- Destructors
It's powerful
- You can inherit from multiple prototypes
- Can extend your object (even if it's not called true inheritance)
- Can pick what you want to inherit or not
Less redundant
- Argues that since JavaScript is not statically typed is less verbose
- Multiple inheritance
Dynamic
You can new properties to prototypes after they are created. You can add new methods to a prototype which will be available to all the objects that delegate to it.
In classical inheritance it is not possible because you cannot modify at runtime a class once it's created