What are the difference among -
First :-
(function () {
var Book = \'hello\';
}());
Second:-
This is called a closure to avoid conflicts with other libraries such as mootools
which are using $
. This way you can ensure to use $
in that function with passing jQuery
as a param.
(function ($) {
$(function () { // Here in this block you can use '$' in place of jQuery
.......
});
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.
Like every other answer has said, in the third function you are passing JQuery
to the function.
I would like to take a moment and explain why the first two are the same.
When you create a function, the name of that function is really a function pointer. For instance, in function foo(){}
, foo
is a pointer to the function that you just made (which explains stuff like this). You dereference that pointer (and thus execute the function) by adding parenthesis at the end of the function name: foo()
.
So if we look at that code again, in number one, first you create the function:
function () {
var Book = 'hello';
}
And then you dereference it, effectively executing the function: ()
In the second example, you surround the entirety of the function creation in parenthesis:
(function () {
var Book = 'hello';
})
This ensures that you perform the creation operation before your next command, which is to dereference the function again: ()
. The parenthesis in this case are not really necessary, as the function will be created before it is executed anyway.
In fact, all three are self executing function's and ti really depends on what you are needing to do.
The only difference between is between 3. 1 and 2 are the same.
The difference with 3 is that you are passing a reference to jquery as an argument. Now all functions inside this annoyomus function have access to jque