Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Values in parentheses after javascript function

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.

like image 593
Andrei Suceava Avatar asked Apr 03 '13 09:04

Andrei Suceava


1 Answers

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.

like image 129
James Allardice Avatar answered Oct 07 '22 11:10

James Allardice