JavaScript and Maps (in that order)

You probably don’t want to use the module pattern.

Every so often I see code (and this includes my old code) which uses the ‘module pattern’.  This is when instead of using a constructor to make an object with a prototype you just create an object, add methods to it, and return it, for instance

You probably don’t want to do this.  Why? Because the benefits don’t outweigh the costs. 

Benefits to the module pattern:

  • Conceptually simpler, especially if you aren’t familiar whit how JavaScript inheritance works.

Benefits to constructor pattern:

  • Faster, JS engines have optimized it.
  • Uses less memory. 
  • instanceof operator works.
  • Can inherent with it easily. 

Two other things differences which I’m calling a wash are

  • monkey patching, which is modifying the prototype method to change current functions, which some people like but I believe is usually an awful idea, can do it with constructors
  • data hiding, which is having truly ‘private’ data, this can be done sorta with constructors but breaks inheritability. I usually consider this bad, but some people like it.

Lest anyone using the module pattern’s feelings get hurt I will point out that I myself have used the module pattern extensively in libraries.   But the good news is that it is easy to switch, step one, have your module object be ‘this’ instead of an empty object and delete the return value

there is no step 2.Well that’s a lie, step 2 for that one would be to go find all the places in your code that called it and add the new keyword, there are 2 other options, capitalize the new constructor and then make a lowercase factory function.

or just use the instanceof trick

I usually use the latter as I find the factory pattern to be more complex with it’s multiple functions, for a final outcome of:

Bear in mind that calling it without new adds another frame to the stack, so should be avoided except when necessary.

If you want to ‘hide data’ your constructor you can do it here like so

but bear in mind that most of the benefits that come form constructors we haven’t realized yet.

To get the most benefits out of using prototypes etc you need to actually use prototypes by moving your method definitions outside of the body of the constructor. 

Note you can’t data hide in this way, and if you need to redefine ‘this’ so it can be used in callbacks you need to do it per method you can’t do it once. But all the functions only get defined once so it is significantly faster.

Note: for the love of God we are not talking about AMD and CommonJS modules, we are talking about an object construction pattern which happens to have the same word in the title, that exists in the wild, sometimes wrapped in an IIFE.