Look at this simplified example:
This pattern is based on the
Object.createmethod which was introduced with ES5 and is a more "natural" choice than classical inheritance.
One common gotcha (that also is valid for classical inheritance) comes into play when you have complex objects in the parent:
What happens here with
schwolf.parts.legs = 1is that - according to the getting rule - the parts object from the base class is returned. Because parts is a complex object it set's it's legs property to 1. And why does this affect all instances? This is the big differnence between prototypal inheritance and Java/C#: prototypes are 'referenced' whereas Java/C# base classes get part of the object and don't share anything with other instances (except for stuff that is explicitely marked as 'static').
Object.assignis just for keeping the example concise):
What are the advantages of this approach?
- easy to grasp - note that we only use functions and no (relatively complicated) prototypes or constructors
- no gotchas
- encapsulation (private members), see nameLength variable in person function
- high performance after object creation
There are unfortunately also some bad news:
- low performance when creating many objects
- less dynamic than prototypal inheritance (prototype augmention not possible at any time like with prototypal inheritance)
- instanceof not possible
But still, in my opinion the advantages of functional inheritance outweight the disadavantages, especially because of the fact that in the vast majority of the real life use cases the mentioned drawbacks are not a really problematic.
Finally a word of caution: do not exaggerate the usage of inheritance, instead adhere to one of the most important OO principles and prefer composition over inheritance!