PDA

View Full Version : Why the anonymous function?



alexf
13 Jun 2007, 4:07 AM
Why do tutorials such as the Using Layouts (http://extjs.com/learn/Tutorial:Using_Layouts_with_Ext_-_Part_1) one use the form:

Simple = function() {
return { /* a closure */ }
}();


rather than simply:

Simple = { /* a closure */ };

Is there some subtlety of javascript which I should be aware of here?

Thanks,

Alex

efege
13 Jun 2007, 4:52 AM
The article by Dustin Diaz "How to achieve private, public, and privileged members in JavaScript" can help understand this subtlety; it's linked from here: http://extjs.com/learn/Manual:Resources#OO_JavaScript

There's also a sticky thread in this forum that addresses your question:

http://extjs.com/forum/showthread.php?t=441

though now I notice that its title (javascript newbie.. help?) is not a clear indication of its content...

alexf
13 Jun 2007, 5:05 AM
Thanks very much for your help!

neror
13 Jun 2007, 7:00 AM
There's also a new article on the YUI blog that gives a quick, simple overview of the pattern.

http://yuiblog.com/blog/2007/06/12/module-pattern/

efege
13 Jun 2007, 7:01 AM
Another one, published just yesterday on YUI Blog: A JavaScript Module Pattern (http://yuiblog.com/blog/2007/06/12/module-pattern/)

The article presents what Douglas Crockford calls the “module pattern”:

1. Create a namespace object
2. Assign the return value of an anonymous function to your namespace object
3. Add “private” methods and variables in the anonymous function prior to the return statement
4. Do something useful with the pattern

And you should not forget to visit http://crockford.com/

EDIT: now I understand why this thread: Alert user if another post is made while adding a response (http://extjs.com/forum/showthread.php?t=7458) ;)
EDIT 2: added link to wiki (http://www.extjs.com/learn/Manual:Resources#OO_JavaScript)