Modules: overriding properties

As we’ve seen in the previous post, we can add properties to an object exposed by a module through a technique known as augmentation. Even though there are some advantages associated with the approach shown (ex.: no need for loading scripts in a specific order), the truth is that we’re out of luck if we need to “override” a property defined in one of the files of the module. As I’ve said, in this case order of loading is important and there’s no way around it (after all, if we’re augmenting a property, it surely must have already been defined before being augmented, right?).

In order to illustrate this approach, we’ll rewrite the previous example. We’ll remove the jQuery dependency and will change the code so that each file defines  a single printValue (file 2 overrides and augments this method). The following snippet shows the code I’ve ended writing in each file (assume we’re using strict mode and that file 1 is loaded before file 2):

//file1
var obj = (function (baseModule) {
    var someValue = "private";
    function printValue(elemSelector) {
        return someValue;
    }
    return {
        printValue: printValue
    };
})();
//file2
(function (baseModule) {
    var someOtherValue = "private 2";
    //save reference to overriden method
    var otherModulePrintAnotherValue = baseModule.printValue;
    function printValueOverride(elemSelector) {
        return otherModulePrintAnotherValue() + "—" + someOtherValue;
    }
    //change reference to new method
    baseModule.printValue = printValueOverride;
})(obj);

If you compare this code with the one we had before, you’ll notice several differences. The most interesting part happens within the anonymous function defined in file2. As you can see, I start by saving a reference to the printValue method which was defined by the module introduced by file1. This reference is used by another function which will end up overriding the initial printValue method. Without this reference, it would be impossible to call the function after performing the override. From now on, you can simply call the overridden function like this (assuming we’ve got an element with ID set to info):

<script>
    "use strict";
    $("#info").text(obj.printValue());
</script>

And that’s it for now. Stay tuned for more.

Advertisements

~ by Luis Abreu on February 14, 2013.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: