Parasitic inheritance
If you like the fact that you can have all kinds of different ways to implement inheritance in JavaScript, and you're hungry for more, here's another one. This pattern, courtesy of Douglas Crockford, is called parasitic inheritance. It's about a function that creates objects by taking all of the functionality from another object into a new one, augmenting the new object, and returning it, "pretending that it has done all the work".
Here's an ordinary object, defined with an object literal, and unaware of the fact that it's soon going to fall victim to parasitism:
vartwoD = { name: '2D shape', dimensions: 2 };
A function that creates triangle objects could:
Use
twoD
object as a prototype of an object calledthat
(similar tothis
for convenience). This can be done in any way you saw previously, for example using theobject()
function or copying all the properties.Augment
that
with more properties.Return
that
.function triangle(s, h) { var that = object(twoD); that.name ='Triangle...