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:
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:
Am I correct, that for providing unobtrusive javascript, the module pattern is ideal?
Short answer. So what's the difference between constructor and prototype? A short answer is that the constructor is a function that is used to create an object, while the prototype is an object that contains properties and methods that are inherited by objects created from a constructor.
The Javascript module pattern enables the implementation of the closure principle providing the control of privacy in your methods so that third party applications or modules cannot access data in variables or overwrite it.
In JavaScript, the Module pattern is used to further emulate the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope.
When a function is created in JavaScript, the JavaScript engine adds a prototype property to the function. This prototype property is an object (called a prototype object) that has a constructor property by default. The constructor property points back to the function on which prototype object is a property.
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)
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With