-1

Am still and again and forever trying to come to grips with javascript. I look at other scripts for inspiration and learning. Does somebody know what this is:

(function(args){})(moreArgs){});

It's the skeleton of jquery. Can somebody explain to me how this works? Thanks!

Here is more of the skeleton:

( function( global, factory ) {

} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

    return jQuery;
} );
Daniela
  • 234
  • 2
  • 13

1 Answers1

0

TLDR; (func)(params); executes a function inplace with out having to assign the function to a separate variable.


Lets break this code down to it's smaller elements. Firstly the whole code is a self executing function. Consider we have a anonymous function.

var add = function (a,b) { return a + b; };

We can call this function like

add(1,2);

however we can also wrap our function in () and call it in the same way.

(add)(1,2);

Both will result in the add function being called. Because JavaScript does not differentiate between function literals and references to anonymous functions we can use the same format to call a function literal.

(function(a,b){ return a + b; }))(1,2);

It's this format your code is using to call the outer function. So why would we want to call a function in this way? Because namespace, or lack there of. JavaScript has a global mutable namespace. Global means that all of the language constructs are available in the same namespace that by default scripts are executed in. This would not be such a problem however everything in this namespace is mutable. So

Array = {};

Would redefine the array constructor function. Any other scripts on your page that are using Array would stop working if they have not already finished executing. This is bad as it yields unpredictable behaviour. So how do we fix this. One way is to place our entire program in a function. When your inside a closed function you no longer are in the global javascript namespace. Your in the function scope and your free to redefine Array if you feel the need(seriously though don't redefine Array).

So we have our function that protects our program form any other's running within a page but we have one problem. We have defined a function however we have not called it. Javascript is executed as it's read. When the VM reads the first line of your js file it will execute that line. This is not true of code with in a function. This code will only execute when the function is called. So as short hand () is added to the end of a defined function to ensure that function is called as soon as it has been loaded by the VM.

Stewart
  • 3,023
  • 2
  • 24
  • 40