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):
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):
And that’s it for now. Stay tuned for more.