Javascript: Module Pattern vs Constructor/Prototype pattern?

时间秒杀一切 提交于 2019-11-27 17:04:35
bobince

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.

intrepidis

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

Prototype pattern helps us to extend the functionality and there is only one instance of functions in a memory irrespective of the number of objects. In Module patter, each object creates a new instance of functions in memory but it provides with concept of private/public variables and helps in encapsulating the variables and functions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!