10

Possible Duplicate:
jQuery: What does (function($) {})(jQuery); mean?

I stumbled up on the following code (included in one file) but I just cannot understand what it really means.

(function ($) {
    function doSomething1(somedata) {

    }

    function doSomething1(somedata) {

    }
})(jQuery);

Question 1: What does this syntax mean in the contex of jQuery

Question 2: How can we call these functions let say from other files such as the HTML index file and other JavaScript files?

Thanks

Community
  • 1
  • 1
mehdi
  • 141
  • 1
  • 1
  • 5
  • 1
    it is a self executing anonymous function. Go through this post http://briancrescimanno.com/2009/09/24/how-self-executing-anonymous-functions-work/ –  Dec 25 '10 at 18:08
  • This question has been asked many times previously – Russ Cam Dec 25 '10 at 18:10
  • 1
    @Russ Cam: It's just too bad it's made up of a bunch of symbols, which is pretty hard to search SO or Google for... – BoltClock Dec 25 '10 at 18:11
  • 1
    The symbols do make it harder to search, but there are still so many, they're easy to find. For example, put this into google `site:stackoverflow.com what does (function($) { mean jQuery` (the url doesn't come out as and anchor link if I pasted directly) – Russ Cam Dec 25 '10 at 18:13

3 Answers3

8

This syntax is not particularly special to jquery, it's normal javascript. Here simply function

function ($) {
    // some code here...
}

(note that it takes argument named $) is called with parameter jQuery (which is, obviously, global object of jQuery framework).

This is usually done when there're several js frameworks on one page (jquery, dojo, prototype, etc) which all redefine global variable $. But with this code, inside doSomething1 or doSomething2 you can always call $('.test') and be certain that call will be processed by jquery, not dojo. Because $ is not a global variable in this case, it's function parameter.

Nikita Rybak
  • 64,889
  • 22
  • 150
  • 172
0

I'm not sure about your question here, but the (function() means it's self-executing,

and you call them by importing the files in the main page and then calling

doSomething1()

Mantar
  • 2,490
  • 5
  • 21
  • 30
0

Mostly likely that was jQuery plugin: Plugins/Authoring

ifaour
  • 37,558
  • 12
  • 70
  • 79