0
\$\begingroup\$

I'm learning about the Javascript module pattern from an array of online sources. The following suits my basic needs at the moment:

var module = function(){
 // Create the return module and its configuration
 var module = {},
 config = {
 css:{
 classes:{
 heading:'h1',
 navbar:'nav-bar'
 },
 ids:{
 widget:'widget',
 block:'block'
 } 
 },
 userName:'user',
 token:'UUID'
 };
 // Private methods
 function _moduleMethod() {
 console.log(config.userName);
 }
 // Add functionality to the module's init()-ialising method
 function init() {
 _moduleMethod();
 }
 // Add init, and any other methods, to obj
 module["init"] = init;
 // Return a the module as a Public API
 return module;
}();
// When the DOM is ready, run the module
document.addEventListener("DOMContentLoaded", function() {
 module.init();
});

My question is regarding the naming of the internal return object the same as the external variable "module". My thinking is that it's OK given closure and scoping but most of the examples I've seen name the internal object something like "obj" or "my". Am I going to run into issues down the line, say with the Augmenting module pattern?

asked Jan 18, 2018 at 2:59
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Because of the scoping inside a closure you will not run into a problem.

The Revealing Module Pattern

I want to introduce this type of module pattern because it does not need the helper object module. Instead of collecting all public functions inside an object called module return directly an object with all public functions. This will reduce code and result in a better to reading code.

var module = function () {
 var config = {
 css: {
 classes: {
 heading: 'h1',
 navbar: 'nav-bar'
 },
 ids: {
 widget: 'widget',
 block: 'block'
 }
 },
 userName: 'user',
 token: 'UUID'
 };
 function _moduleMethod() {
 console.log(config.userName);
 }
 function init() {
 _moduleMethod();
 }
 // Return an object as public API
 return {
 init: init 
 }
}();
answered Jan 19, 2018 at 7:30
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.