0

I have never seen this design pattern before, what is it doing?

(function(def){
    if(typeof module!='undefined'){
        module.exports=def;
    }
    else{
        this.nut=def;
    }
}( function(){
   ...
}() ));
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
  • 2
    Passing one anonymous function into another. – TheZ Aug 08 '12 at 20:25
  • Are you asking why a function is passed to the other function, or how the whole construct (`(function(foo) {...}(bar))`) works? Probably a duplicate of http://stackoverflow.com/questions/592396/what-is-the-purpose-of-a-self-executing-function-in-javascript. – Felix Kling Aug 08 '12 at 20:25
  • 2
    Seems like an overly complicated way to make a module that falls back to being a global in environments without CommonJS module support. – Esailija Aug 08 '12 at 20:28
  • @FelixKling I am asking why, I don't see why you can't just define a function like normal. – Billy Moon Aug 08 '12 at 20:34

2 Answers2

2

This is a "immediately invoked function expression", as Ben Alman would say. The first function defined takes one argument, def. Wrapping this function in parantheses and passing it a second function definition (also in parentheses) immediately invokes the first function, passing it the result of the second function (it is also immediately invoked) as the def parameter.

More information: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

jackwanders
  • 15,612
  • 3
  • 40
  • 40
1

lets decode it step by step

function(def)
{
    if(typeof module!='undefined'){
        module.exports=def;
    }
    else{
        this.nut=def;
    }
}( function(){}());

//the outer brackets removed now as u can see a function is defined which is a normal way to define a function
which takes one argument def
immediately after the definition there is a bracket
so if we breakit down further then

function(def) //function 1
    {
        if(typeof module!='undefined'){
            module.exports=def;
        }
        else{
            this.nut=def;
        }
    }( function() /*function 2*/{}());

this simply means that second function is passed as a parameter to the first function
a bracket () just after the definition of a function in JS signifies that that function here function 1 will be call immediately after the definition. and what ever is inside the brackets will be passed to the function as parameter so def basically is function2

Parv Sharma
  • 12,581
  • 4
  • 48
  • 80