On 12/11/10, Diego Souza <[email protected]> wrote: [snip[
> 2010/12/7 Rey Bango <[email protected]> > >> Hi guys, >> >> Angus Croll just posted a great article about namespacing in JavaScript. >> Definitely worth the read: >> >> http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/ A lot of missing semicolons there. I don't like the idea of setting global properties `next` and `reset` as methods of the `window`. And what's `myApp = {};` got to do with any of that anyway? Seems irrelevant for this example: 01 var myApp = {}; 02 (function(context) { 03 var id = 0; 04 05 context.next = function() { 06 return id++; 07 }; 08 09 context.reset = function() { 10 id = 0; 11 } 12 })(this); The article advocates the use of `apply` to "provide natural separation of context and arguments". I don't see any advantage there. 01 var myApp = {}; 02 (function() { 03 var id = 0; 04 05 this.next = function() { 06 return id++; 07 }; 08 09 this.reset = function() { 10 id = 0; 11 } 12 }).apply(myApp) 13 14 window.console && console.log( 15 myApp.next(), 16 myApp.next(), 17 myApp.reset(), 18 myApp.next() 19 ) //0, 1, undefined, 0 That way requires a few eyeball scans up and down the code. It isn't the end of the world but I would rather just use NewExpression. var counter = new function() { var i = 0; this.next = next; function next() { return i++; } }; With NewExpression, the beginning shows that the context is a new object creation and that the method assignments that fall below are definitely going to be on that object. I like the way it reads, top-down. To me, NewExpression seems clearer than saying "create an object, then create a FunctionExpression, then call that FunctionExpression using `apply` and passing in the new object. -- Garrett _______________________________________________ JSMentors mailing list [email protected] http://jsmentors.com/mailman/listinfo/jsmentors_jsmentors.com List Archive: http://jsmentors.com/pipermail/jsmentors_jsmentors.com/
