What is the module pattern in JavaScript

Javascript module pattern - Can all modules access each other? - Javascript, design pattern

I've done quite a bit with vanilla javascript and jquery. I am now trying to write an app that will privatize methods using closures so that everything is not in the public namespace.

I turned to the module pattern because it seemed to be the solution to my problems, but I can't really take care of it. If you use this pattern to add methods to the main app, can all modules use all methods from other modules? that does not seem to be the case.

For some reason, I would expect to comment on the method to work. Can we let this work? I envision having an app.js with the meat of an app, along with other separate js files that have utility functions to help that app, but in many cases I envision these utility classes having access to the The main app need section "can't seem to get that ...


Someone I spoke to referred me to Browserify.js, but I don't know if that solves my requirement that everything is inaccessible through locks. It seems like a bundling app.


0 for the answer № 1

Your problem is that you don't adhere to Object-oriented design rules. There are different paradigms and more books, blogs and videos than you could consume in 10 lifetimes. Personally, I recommend the SOLID principles for OOP.

In particular, your modules should be encapsulated units. A module should have a single logical responsibility that should be disclosed through its public methods. If you need access to the private methods, then there is a design problem.

0 for the answer № 2

The ad hoc module pattern gives you the opportunity to create privacy by including a value in a function, i.e. a degree.

Think about it like this:

If you declare a variable within a function, it can only be accessed in that function unless you make it available.

Unexpectedly, _foo just sits there and waits for the garbage collector

Exposed, name is exposed, but age is not. You cannot access _foo directly. The code under age is useless because it cannot be reached.

If you create another constructor, bar, it won't be able to interact with _foo because it's wrapped in myFoo. The bar API can only access variables defined in it, in this case _bar.

Information bar makes full use of private data. It might be a good idea to add setters.

This pattern offers privacy, the architecture of how you structure your app is entirely up to you.

See this book for comprehensive examples of basic Javascript patterns: https://addyosmani.com/resources/essentialjsdesignpatterns/book/