2

The Module pattern is used to mimic the concept of classes (since JavaScript doesn’t natively support classes) so that we can store both public and private methods and variables inside a single object.

Is this still pattern still necessary now that javascript has it's own native classes?

jsldnppl
  • 915
  • 1
  • 9
  • 28
  • 3
    The module pattern does not mimic classes at all. It is used for creating single values (functions, namespace objects, classes, singletons, whatever) with access to a local scope. Classes are "mimicked" (if you will) by the constructor+prototype approach. – Bergi Dec 08 '17 at 13:15
  • 2
    I still use this pattern in ES6, mostly when I want to limit the scope of some variables. – sp00m Dec 08 '17 at 13:20
  • 2
    Related: [Will const and let make the IIFE pattern unnecessary?](https://stackoverflow.com/q/33534485/1048572) – Bergi Dec 08 '17 at 13:21

1 Answers1

2

The module pattern isn't only (or even primarily) used to mimic classes. It's proper modules, not classes, that make the old module pattern likely to become...if not obsolete, then a lot less-used, in the next few years. Those and private methods (which are currently a Stage 3 proposal) and perhaps to an extent private fields (also Stage 3).

But prior to proper modules, or sometimes even concurrent with them, you'd still use it if you want to have private functions or data or similar related to something which isn't private. Example:

const Foo = (function() {
    function privateFunction(x) {
        return /*...do something with `x`...*/;
    }

    class Foo {
        dosomething(x) {
            return privateFunction(x) ? "a" : "b";
        }
    }
    return Foo;
})();

I'll also note that sometimes, you might use an anonymous block rather than an IIFE, since class, const, and let have block scope. I wouldn't above because I'd have to make the outer Foo non-constant (so I could assign to it in the block), but there are other times when it might apply...

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875