Javascript: Module Pattern vs Constructor/Prototype pattern?

I would like to know if the module pattern or Constructor/protoType pattern is more applicable to my work.

Basically I am using unobtrusive javascript -- the HTML document has a reference to the .js file.

My understanding of the module pattern:

  • call an INIT method (which is basically a public method i can create and return using the module pattern)
  • In the INIT method, assign all click events etc.
  • This sounds like the perfect pattern for my situation, as I don't need to create Objects and inheritance hierarchies etc.

    My understanding of the Constructor/Prototype pattern:

  • for creating objects
  • for using inheritance (ie Subtypes of a supertype)
  • Am I correct, that for providing unobtrusive javascript, the module pattern is ideal?


    Constructor-functions and prototypes are one of the reasonable ways to implement classes and instances. They don't quite correspond to that model so you typically need to choose a particular scheme or helper method to implement classes in terms of prototypes. (Some background on classes in JS.)

    The module pattern is typically used for namespacing, where you'll have a single instance acting as a store to group related functions and objects. This is a different use case from what prototyping is good for. They're not really competing with each other; you can quite happily use both together (eg put a constructor-function inside a module and say new MyNamespace.MyModule.MyClass(arguments) ).


    Module pattern is by far easier and more elegant than prototype. However, thinking mobile first. It is not a relevant pattern for medium/large objects because the initialization needs to parse the whole block before starting. The multiple closures also create circular dependencies that the garbage collector does not free (especially IE), it results in a heavier memory footprint not freed until the window (or tab) is closed - check chrome task manager to compare- The loading time is inversely proportional to the object size using module pattern while this is not the case for prototypal inheritance. Statements above are verified through multiple benchmarks like this one: http://jsperf.com/prototypal-performance/54

    As seen in last test. Small objects are better off being initialized as plain object ( without these patterns). It is suitable for single objects not requiring closure nor inheritance. It is wise to assess if you even need these patterns.


    You could try the Folding Pattern, here's a link: Javascript Folding Pattern

    I also left an answer to a similar question, which shows how to use the Folding Pattern:

    Simple Example of Folding Pattern

    链接地址: http://www.djcxy.com/p/50130.html

    上一篇: 使用模块模式的JavaScript类原型

    下一篇: Javascript:模块模式vs构造函数/原型模式?