0

When using the Module pattern to extend a module we do something like this:

var NewModule = (function (Main) {

    Main.extension = function () {};
    return Main;

})(Main || {});

That works great and the question is, if Main is not declared we avoid errors by passing an empty object Main || {}. How do we prevent this dependency from breaking? Granted, we wont have any errors at first but if we are not able to attach our extension to Main we will encounter other type of errors.

7
  • Is the desire to occasionally call it with no arguments and get an object with the extension methods? Commented Sep 7, 2017 at 17:07
  • probably better ways of doing it but my immediate feeling is just, i'm guessing, either a) fatal err if your root dependency is missing (rather than ignoring it and passing an empty object) or b) check for missing dependencies everywhere else with the roots siblings Commented Sep 7, 2017 at 17:09
  • @RobM. That is correct, the main goal is for Main to have all the methods available when needed in the future. Commented Sep 7, 2017 at 17:10
  • @mad.meesh, yeah I thought about having a hard stop if Main object is not present at the application level but yet again leave some sort of flexibility for unit testing. Commented Sep 7, 2017 at 17:12
  • ah if this issue is specific to unit testing then i believe you need to solve this with 'mock objects' and such, have you already consider this? also another way of saying it is to build your abstractions based on behavior (interfaces) Commented Sep 7, 2017 at 17:14

1 Answer 1

1

If the goal is to extend Main, you usually wouldn't assign to NewModule. You'd rather do

// a.js
var Main = (function (localMain) {
    localMain.extensionA = function () {};
    return localMain;
})(Main || {});

We do this so that we can have multiple modules like that:

// b.js
var Main = (function (localMain) {
    localMain.extensionB = function () {};
    return localMain;
})(Main || {});

All of them will either create or extend the Main object, so that it doesn't matter in which order they load - both a.js, b.js and b.js, a.js will work. The pattern is also sometimes simplified to

(function (localMain) {
    localMain.extension = function () {};
})(Main = Main || {});

(although that lacks the var declaration).

If your module (especially your newModule) does have an actual dependency on the main module, and requires that it was loaded before it is executed, you would not use this defaulting pattern.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.