Question

I am a little confused here. Following the module pattern in JS, a module is normally a returned object from an anonymous function that is immediately executed. But what if I don't want to execute the function and instead call it whenever I need to e.g. window.onload.

var module = function (args) {
    //private members

    return {
         //public members
    };
};

var module_instance = module (args);   // module instance or facade instance?

Are there any problems with this implementation? Is there a different, more efficient way to do this?

Also, following the previos block of code, what if I call the function again and asign the returned value to another variable:

var module_instance2 = module (args);

does that mean I now have a 2nd facade of the function or is it a new function altogether?

Cheers!

Was it helpful?

Solution

That function is the constructor of your module so each time you call that function, a new separate instance of the module is created and assigned to the receiving variable.

There is not any problem with this implementation (actually it is very common,), and you can use it wherever in your program to obtain a new instance of that module.

Best.

OTHER TIPS

The module pattern is similar to namespaces in other languages, and is used to prevent global variable pollution and as a method of encapsulation.

window.module1 = (function() {} {
  var version = "0.0.1";
  function func1 () {};
  function func2 () {};

  return = {
    version: version,
    func1: func1,
    func2: func2,
  };
})()

You could have a Function DeclareModule() that defines a module on the window object.

var DeclareModule = function(name, content) {
  if (typeof content === 'object') {
    window[name] = content;
  } else if (typeof content === 'function') {
    window[name] = content();
  }
};

//Declared by object
DeclareModule("module1", {
  version: "0.0.1",
  func1: function () {},
  func2: function () {}
});

//Declared by function
DeclareModule("module1", function () {
  var version = "0.0.1";
  function func1 () {};
  function func2 () {};

  return {
    version: version,
    func1: func1,
    func2: func2
  };
});

Have a look at AMD and CommonJS modules, or an article by Addy Osmani.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top