Dear Lazy Web, should I use “functional inheritance” or prototypal inheritance?
Is see the following advantages of the use of the functional inheritance pattern:
- simplicity: a few steps are required to achieve inheritance ;
- “this”-free: you don’t have to care with the context variable “this”, meaning that you can freely pass any method of a functional object as a callback parameter and everything will work as expected (see this script, for example) ;
- encapsulation: objects can have private (and even protected) members.
In prototypal inheritance, objects are created using the
new keyword, and inheritance is achieved by linking the object’s prototype to another object’s prototype. Example:
I see the following advantages of the use of the prototypal inheritance pattern:
- performance: prototypal object creation involves less steps than functional objects creation, thus prototypal object creation is faster than functional object creation (by several orders of magnitude, as you’ll see below) ;
- dynamsim: one can add methods to a prototype at any time and these methods will automatically be available on all objects inheriting this prototype ;
- reflection: though this is not very important, you can test if an object is of some type by using the
instanceofoperator, which is not feasible with functional inheritance.
At this point of the review, the choice is really hard because on one hand we have a simple and trap-free system (functional inheritance) which just does well the job, and on the other hand a faster and more flexible system (prototypal inheritance) but less straightforward to use (inheriting from a class needs to both call the ancestor constructor and the
inherits function) and, even worse, more error prone since you cannot pass an object’s method as a callback parameter unless you explicitly take care of wrapping it in a function ensuring that its execution will be performed using the right context (try it here!).
I’d love to use the prototypal inheritance pattern if it was possible to simplify its usage and to automatically take care of binding methods on the right context object.
=>”, to define them).
However, I wrote a little benchmark measuring object creation time and method call performance when using either functional inheritance, prototypal inheritance or prototypal inheritance with all methods bound to the instance object (a la CoffeeScript). Here is the interpretation of the results:
- prototypal object creation is more than 100 times faster than functional object creation. However, when prototypal objects methods are forced to be bound to their instance, the prototypal object creation is about as fast as functional object creation ;
- methods calls are always faster using functional inheritance, and binding prototypal objects methods to their instance decreases performance even more.
That’s why I think I’ll use functional inheritance. Unless someone sees a better solution?