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 called that (similar to this for convenience). This can be done in any way you saw previously, for example using the object() 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 () {return this.side * this.height / 2;};
    that.side = s;
    that.height = h;
    return that;
    }

Because triangle() is a normal function, not a constructor, it doesn't require the new operator. But because it returns an object, calling it with new by mistake works too.

>var t = triangle(5, 10);
>t.dimensions;
2
>vart2 = new triangle(5,5);
>t2.getArea();
12.5

Note, that that is just a name; it doesn't have a special meaning, the way this does.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.166.98