Reputation: 58601
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(){
...
}() ));
Upvotes: 0
Views: 76
Reputation: 12705
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
Upvotes: 1
Reputation: 16040
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/
Upvotes: 2