On 06/Dec/10 6:14 PM, Casey Goodhew wrote:
Out of curiosity Marko, why would you avoid the "new"? I'm not against
it, just looking for the reasoning (we use this pattern in our code
quite a bit).
Here's why I wouldn't use new /in this case/. Not because it is
redundant, but because it is misleading. By reading the first line...
var nc = new function() {
...you'd expect nc to be an instance of that anonymous constructor, but
it isn't. It's actually an instance of the that object-literal returned
at the end of the constructor.
Normally, I would like the `var nc = new function ()` idiom. I like it
because it offers more visual cue than `var nc = (function ()` about the
pattern you're using (module). And you'd be able to write your public
API by augmenting `this` (another visual cue), while keeping the
"private" members declared using `var`.
var nc = new function () {
var privateMember = 1;
this.publicMember = 2;
};
I also like it because this syntax is much more flexible than the
object-literal notation. You can actually write something like:
this.addEvent = (function () {
// use feature detection to determine the correct native
// method and return a function that delegates to it.
})();
I don't like it because, as I said, the JS community (myself included)
is already accustomed to the module pattern. I also don't like it
because it might create readability problems when there are other
`this.member` declaration in "sub-modules", and the only visual cue
would be indentation. A third reason would be that, if the final return
in the classic module pattern would be kept to a minimum, then the API
is even easier to read (this rarely happens):
var nc = (function () {
var create = ...
var read = ...
var update = ...
var remove = ...
// Easier to glance over the public API
return {
create: create,
read: read,
update: update,
remove: remove
};
})();
If you have any other pros/cons, I'd be glad to know about them. But
please, don't tell me that jslint thinks it's a weird construction.
--
Ionuț G. Stan | http://igstan.ro
_______________________________________________
JSMentors mailing list
JSMentors@jsmentors.com
http://jsmentors.com/mailman/listinfo/jsmentors_jsmentors.com