Can someone please explain the differences between the following functions:
(function($){ // can do something like $.fn.function_name = function(x){}; })(jQuery);
Could I use jQuery in the next function?
(function(){ }());
And is the following the same as jquery.ready()?
$(function(){ });
Thanks!
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
A Closure is a combination of a function enclosed with references to its surrounding state (the lexical environment). In JavaScript, closures are created every time a function is created at run time. In other words, a closure is just a fancy name for a function that remembers the external things used inside it.
In JavaScript, a closure is a function that references variables in the outer scope from its inner scope. The closure preserves the outer scope inside its inner scope.
In JavaScript, closures are defined as inner functions that have access to variables and parameters of outer function even after the outer function has returned.
(function($){ // can do something like $.fn.function_name = function(x){}; })(jQuery);
That is self-executing anonymous function that uses $
in argument so that you can use it ($
) instead of jQuery
inside that function and without the fear of conflicting with other libraries because in other libraries too $
has special meaning. That pattern is especially useful when writing jQuery plugins.
You can write any character there instead of $
too:
(function(j){ // can do something like j.fn.function_name = function(x){}; })(jQuery);
Here j
will automatically catch up jQuery specified at the end (jQuery)
. Or you can leave out the argument completely but then you will have to use jQuery
keyword all around instead of $
with no fear of collision still. So $
is wrapped in the argument for short-hand so that you can write $
instead of jQuery
all around inside that function.
(function(){ }());
That is self-executing anonymous function again but with no arguments and runs/calls itself because of ()
at the end.
That patterns turns out to be extremely useful in some situations. For example, let's say you want to run a piece of code after 500 milli seconds each time, you would naturally go for setInterval
.
setInterval(doStuff, 500);
But what if doStuff
function takes more than 500 mill-seconds to do what it is doing? You would witness unexpected results but setInterval
will keep on calling that function again and again at specified time irrespective of whether doStuff
finished.
That is where that pattern comes in and you can do the same thing with setTimeout
in combination with self-executing anonymous function and avoid bad setInterval
like this:
(function foo(){ doStuff; setTimeout(foo, 500); })()
This code will also repeat itself again and again with one difference. setTimeout
will never get triggered unless doStuff
is finished. A much better approach than using bad setInterval
.
You can test it here.
Note that you can also write self-executing anonymous function like this:
function(){ // some code }();
Using extra braces around (like before function
keyword) is simply coding convention and can be seen in Crackford's writings, jQuery and elsewhere.
$(function(){ });
That is short-hand syntax for ready handler:
$(document).ready(function(){ });
More Information:
I know that this question is old, but I stumbled upon it right now and so may other people. I just wanted to point out that, although Sarfraz's answer is great, it has to be said that no, writing a self-executing, anonymous function within braces is not a coding convention.
function(){ // some code }();
Will not work and give out a SyntaxError
because the function is being parsed as a FunctionDeclaration
, and the function name is not optional in this case.
On the other hand, the Grouping Operator makes sure that the content is evaluated as a FunctionExpression
.
See: Explain JavaScript's encapsulated anonymous function syntax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With