Understanding prototypal inheritance in JavaScript - Part 4

In the previous installment of the prototypal inheritance series we have seen how to derive an object to extend the functionality of the prorotype object. Today we will explore some implications of wat we saw in the previous posts.

Let's pretend that you are creating a plugin based game development library (any reference to friGame is purely intentional), and the plugins can extend the functionality of the sprites.

Let's see once again the code that we used to create the Sprite Prototype Object:

var PSprite = Object.create(PRect);
$.extend(PSprite, {
    init: function (options) {
        // Initialize the base object
        PRect.init.call(this, options);

        // Initialize the object
    },

    setAnimation: function (options) {
        // Set the sprite animation
    }
});

The Sprite derives from Rect, it overrides the init method, and it explicitly calls the overridden method. So far, so good.

Now, let's pretend that a plugin needs to make some more operations inside the setAnimation method, other than those defined in the Sprite Prototype Object.

We cannot make a derived object, as the users of the library don't know about the derived object, so they will continue to use the Sprite, without the additional functionality provided by the plugin. Moreover, what if 2 plugins extend the functionality of the setAnimation method (and obviously, these 2 plugins don't know anything about each other)?

Well, the solution here is simple: you don't have to make a derived object in order to override a method.

Being JavaScript a dynamic language, the functions can be assigned to any object, and overridden without limitations, so we can save the overridden method in a different object, override the method, and call the overridden method from the different object like this:

var overrides = {
    setAnimation: PSprite.setAnimation  // Save the function to override
};

$.extend(PSprite, {
    setAnimation: function (options) {
        // Call the overridden method
        overrides.setAnimation.call(this, options);
    }
});

Now this may sound dangerous, especially if you are not used to dynamic languages, but in reality this is not different at all than overriding a method from a derived object.

Well, there is in fact a danger to this technique, that is that if 2 plugins, that know nothing about each other, override the same method, they can change the functionality in incompatible ways, but, at least from my experience with friGame, this has never happened.

This post concludes the Prototypal Inheritance series, but there are some news concerning Cownado and Frank the Dillo, so stay tuned.

Comments !