On Jan 8, 2008 11:20 PM, Simon Thomas <[EMAIL PROTECTED]> wrote:
> Can anyone explain the difference in the folllowing and when and why
> to use each of the methods.
> (Or knows a better place to ask this question)
> 1)
> var myVar = function(args){
>    // inner functions and vars
> };

This makes myVar point to that function, so you can later call
myVar(args), it's a normal function declaration and it's almost
equivalent to
doing function myVar(args) { ... }. As functions are first-order
citizens in JavaScript, you can just assign them to a variable.

> 2)
> var myVar = (function(args){
>    // inner functions and vars
> });

This is exactly the same as (1). As any object in JS, a function can
be wrapped in parenthesis with no consequence.

> 3)
> var myVar = (function(args){
>    return {
>    //inner functions and vars
>   }
> })();

This will declare an anonymous function that receives "args" (only one
argument), and *immediately after declaring it* it will call it
passing *no arguments*. So if you depend on args inside the function
that will error out. Since it executes it, myVar will point to
whatever the function returns.

This technique was called "The Module Pattern" by Douglas Crockford,
and has been described throughly in the interweb:
- http://yuiblog.com/blog/2007/06/12/module-pattern/
- http://wait-till-i.com/2007/07/24/show-love-to-the-module-pattern/


> >

You received this message because you are subscribed to the Google Groups 
"Prototype: Core" group.
To post to this group, send email to prototype-core@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 

Reply via email to