4

I don't understand what the last line of code is doing here. It looks like random parenthesis tagged at the end of the function. I don't understand the syntax.

(function (self, $, undefined) {
    self.methodName = function () {
        //do stuff
    }
})(This.IsTheNameOf.MyJsFile, Jquery);

What I do know: self = namespace organization tool. $ = JQuery. The first thing in the last line of code is the name of the JS file that contains this code. The last line obviously isn't a function call, but it seems to coincide with self and $.

Any knowledge is greatly appreciated!

JJJ
  • 32,902
  • 20
  • 89
  • 102
lonious
  • 676
  • 9
  • 25
  • 1
    It's an IIFE that passes arguments, and `Jquery` should probably be `jQuery` – adeneo Nov 29 '13 at 21:56
  • 1
    It's a self-executing function, and those are _arguments_ passed to it. – Michael Berkowski Nov 29 '13 at 21:58
  • Thanks guys! Didn't think to search with the actual code. Wouldn't expect to see code in a title but I guess it's brief enough, the second question at the top answers my question as well as adeno and Ingo! – lonious Nov 29 '13 at 22:04
  • out of votes -- duplicate of [Values in parentheses after javascript function](http://stackoverflow.com/q/15783044/218196) – Felix Kling Nov 29 '13 at 22:07

1 Answers1

3

Leaving out some stuff we have

function (self, $, undefined) {
    // ...
}

So, basically, a function (though a name is missing). Now this gets wrapped in

(/* above code here */)(...);

This is a so-called IIFE (Immediately-Invoked Function Expression). In other words: The function is created and immediately invoked. The reason for this is that it creates a scope in which you can have "private" variables. Also, jQuery gets aliased to $ inside that scope for easy reference. Similarly, This.IsTheNameOf.MyJsFile gets aliased to self.

If you look closely, the function expects three arguments, but is only called with two. This forces the last argument to be (the native) undefined, which happens to be the name of that parameter inside the IIFE. This ensures that undefined, inside that scope, has the expected value (older browsers allowed to overwrite it).

Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
  • 1
    You're welcome. Please do look into the links provided by others as they likely contain more information (there is much more that can be said about IIFEs). Please also consider accepting an answer (though, of course, you can wait for more answers). – Ingo Bürk Nov 29 '13 at 22:02