0

I'm a beginner in programming and I just wonder about one thing. To be exact the syntax of (function(){...}).()

This question has been probably asked but as I don't know what it is and how to call it, I had very small luck finding anything about this topic.

I have been checking some scripts lately and I noticed that in some of them people use:

(function(){
   ...
}).(something) // 

So far I'm guessing it's something like function which calls itself right away? How do we use it and what are the advantages of this. What do I put inside where 'something' is? also sometimes before it starts it also has $ sign.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Tomasz Golinski
  • 743
  • 5
  • 25

4 Answers4

1

Your first example is an anonymous self-invoked function. So you are right, it calls itself straight away. If it had a name, that name would ONLY be visible inside those brackets (..).

The dollar-sign functions are short-hand for jQuery calls.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Samuel O'Malley
  • 3,471
  • 1
  • 23
  • 41
1

Imagine a normal function:

function foo(){
    ...
}

Now let's call that function:

foo();

Instead of calling the function using its name, let's call it directly:

(function foo(){
    ...
})();

Since I don't use this function any where else, let's remove its name:

(function(){
    ...
})();

Want to pass a parameter to the function? Sure!

(function(something){
    ...
})(something);

Advantage of this? We have a scope!

(function(something){
    var bar = 5; // Can't access this outside the function
})(something);

This allows you to define stuff outside of the global scope.

Vic
  • 8,261
  • 6
  • 42
  • 55
  • thanks! answered all my questions and more :) appreciate that mate. – Tomasz Golinski Oct 30 '13 at 03:55
  • Vic has explained accurately. If you want to explore more visit [JavaScript Module Pattern: In-Depth](http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html) – Mozak Oct 30 '13 at 04:29
0

You are correct in that it a function that calls itself immediately, also called a self executing function.

The $ is just shorthand using jquery.

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
0

function(){} is declaring a function, while when we do

$(function() {}) it means we pass a function into another function $() as parameter, where this function will be executed by $() when the times met

it is much like

var a = function() { do something }
a();

will do something, in C# its like delegate, while in C++ it is like function pointer, in javascript it is made simple though where you can directly embed a function at the position where a parameter should be

lostincomputer2
  • 353
  • 4
  • 12