Sunday, July 12, 2015

JavaScript Inheritance Best Practices

Many sources document two major techniques and many minor variations to implement inheritance in JavaScript: constructors and prototypes. But constructors and prototypes are not exclusive, in fact they are inclusive and should always be used together. If you just use constructors or you just use prototypes, then you only did half of the job...

The best practices for JavaScript inheritance are:
  1. Move all of your methods out of the constructors and into the prototypes.
  2. Always define all of your properties in the prototype, it helps to document the new "type."
  3. Always use Object.create to link a new object to the "super-type" prototype, never build an instance of the "super-type" as the new prototype object. And always recreate the constructor property in the prototype.
  4. And always chain the constructor calls to the "super-type" constructor, even if they do not take any arguments and may not even do anything.
To explain them we are going to start from the beginning: