14

I'm trying to re-purpose some Javascript code I found linked in an answer on SO. But I would like to understand its syntax better first. Its outline is:

(function (root, ns, factory) {
    // some code
} (window, 'detectZoom', function() {
    // some more code
}));

See accepted answer in this post for the reference to the full code.

I understand how the end-result is achieved, but I don't quite know how the inner (...) block relates to the first, or what the comma separated list inside it tells the compiler.

Can someone explain? Thanks.

Community
  • 1
  • 1
Andrei Suceava
  • 307
  • 2
  • 14

3 Answers3

16

There is an anonymous function taking three parameters (root, ns, factory) which is immediately invoked.

  • root takes the value of`window.
  • ns takes the value of 'detectZoom'
  • factory takes the value of callback function (also anonymous)

The explanation:

(function (root, ns, factory) {
   // the body of the anonymous function
} (window, 'detectZoom', function() {
   // the body of the 'factory' callback
}));

To break it apart, how to get to this code in four steps:

 1.
 // Anonymous function.
 (function (root, ns, factory) {/* body */});

 2.
 // Anonynmous function, immediately invoked
 (function (root, ns, factory) {/* body */})();  // parentheses mean it's invoked

 3.
 // Callback as a separate argument
 var cbk = function () {};
 (function (root, ns, factory) {/* body */})(window, 'detectZoom', cbk);

 4.
 // Callback as an anonymous function
 (function (root, ns, factory) {/* body */})(window, 'detectZoom', function () {});

You could rewrite your code to be more verbose:

var outer = function (root, ns, factory) {
  // the body
};

var callback = function () {
  // the body
};

outer(window, 'detectZoom', callback);
kamituel
  • 34,606
  • 6
  • 81
  • 98
11

What you have is a immediately-invoked function expression (IIFE). If you strip out all the arguments you're just left with this:

(function () {
    // some code
}());

The function expects three arguments:

(function (root, ns, factory) {
    // some code
}());

And you pass it three arguments:

(function (root, ns, factory) {
    // some code
} (window, 'detectZoom', function() {
    // some more code
}));

One of those arguments, factory, happens to be a function.

Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
James Allardice
  • 164,175
  • 21
  • 332
  • 312
1

It creates an anonymous (unnamed) function that accepts three parameters:

function (root, ns, factory) {
    // some code
}

Then immediately calls that function passing three arguments, the third one being another anonymous function:

(window, 'detectZoom', function() {
    // some more code
})

The two blocks need to be wrapped inside a pair of (); the reason is explained here:
Explain JavaScript's encapsulated anonymous function syntax

Community
  • 1
  • 1
Salman A
  • 262,204
  • 82
  • 430
  • 521