views:

60

answers:

1

Hi there,

I have been reading a little bit about the Module pattern and i wonder if applicable for what i need to do or should i use the Constructor/protoType pattern.

Basically I am using unobstrusive javascript so i have a reference to my .JS file in my HTML document.

If i understand it correctly then I can call a INIT method (which is badically a public method i can create and return using the module pattern).

In the INIT method i will assign all my click events etc etc...

THis sounds like the perfect pattern, as i don't need to create Objects and inheritance/supertypes etc

From what i understand the Constructor/Prototype pattern is my for create objects and using inheritance i.e. Subtypes of a supertype??

Am i correct here?

So to provide basic unobstrusive javascript the module pattern is ideal??

I would appreciate any feedback with regards to the right direction to take

Thanks in advance

+1  A: 

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 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 to what prototyping is good for. They're not really ‘vs’ each other, you can quite happily use both together (eg put a constructor-function inside a module and say new MyNamespace.MyModule.MyClass(arguments)).

bobince
so in my case i don't really want to create instances so the module pattern is probably ideal for what i want. When you say namespacing.. How do i namespace in a module pattern? I saw one way using YUI - but is it really necessary?
Martin
There's no particular trick, you just use a JavaScript `Object` as a lookup. Either create an object literal directly like `var MyModule= { someProperty: 3, someFunction: function() { ... }, somethingElse: null };` or assign to `MyModule.someFunction= function() { ... };`. If you want private variables you do it in an immediately-called-function-expression and have that `return` an object in a closure... personally I find ‘real’ private variables a complete waste of time.
bobince