I f 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 basically means that you can have a function that creates objects by taking all of the functionality of another object, augmenting it 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 is soon going to fall victim to parasitism:
var twoD = { name: '2D shape', dimensions: 2 };
A function that creates triangle objects could:
Clone the
twoD
object into an object calledthat
. This can be done in any way you saw above, 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'; that.getArea = function(...