Using Self Calling Anonymous Functions and $(document).ready - javascript

I just recently learned about self calling anonymous functions. Some snippets of code that I came across used the self calling function along with the $(document).ready. It seems redundant, or pointless, to use both.
Is there a case where you'd use
(function(){
$(document).ready();
})();
vs.
$(document).ready(function(){
(function(){})();
});
I figure that you'd either want the script to be executed right away or after the DOM loaded. I can't see why you'd use both together.
Thanks.

There's definitely a use case for the first example. If you have other JS libraries/scripts loaded on the same page, there's no guarantee that they aren't overwriting the $ variable. (This is very common when you have Prototype and jQuery on the same page).
So if Prototype is using $, you would need to use jQuery anytime you wanted to work with jQuery. This can get quite ugly:
jQuery(function(){
jQuery('a', '#content').bind('click', function(){
if(jQuery(this).attr('href') == 'www.google.com')
{
alert("This link goes to Google");
jQuery(this).addClass('clicked'));
}
});
})
Remember, we can't use $ because that is a method from Prototype in the global scope.
But if you wrapped it inside of this..
(function($){
$(function(){
// your code here
});
})(jQuery);
The $ would actually reference the jQuery library inside while still referring to Prototype on the outside! This can help tidy up your code:
(function($){
$(function{}(
jQuery('a', '#content').bind('click', function(){
if(jQuery(this).attr('href') == 'www.google.com')
{
alert("This link goes to Google");
jQuery(this).addClass('clicked'));
}
});
));
})(jQuery);
This is a common pattern with jQuery extensions to ensure that they are always added to the jQuery object, but can be written using $ to keep the code tidy.

You wouldn't want to use both together, is there something you're doing that requires you to?
In the jquery api documentation here, http://api.jquery.com/ready/, you can see these examples:
The .ready() method is typically used with an anonymous function:
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
But I'm not sure if this answers your question because I don't see where you actually ask one. Hope this helps just the same!

The only reason you would introduce another closure is to introduce another scope boundary for loading / protecting global objects such as $.
For Example:
$(document).ready(function(){
// Do upper scope things.
(function(){
// Do lower scope things.
})();
});
Based on you saying you have recently learning about this stuff I assume you are relativly new to JavaScript.
I have put together a blog post that might help explaining some of the basic concepts form the point of view of a newcomer to JavaScript, including function scope. http://bit.ly/tLkykX

Related

Are there any benefits to writing a jquery onload function like this?

This is a piece of code that a colleague of mine uses whenever he writes javascript. Are there any benefits from a 'no conflict with other libraries' point of view to doing it this way?
jQuery((function($) {
return function () {
// code here
};
}(jQuery)));
This is actually a combination of the self-executing anonymous function pattern
(function(window, document, $, undefined){
...
}(window, document, jQuery));
and the jQuery shorthand for document.ready:
jQuery(function($){
...
});
To get all the advantages you could do:
jQuery(
(function(window, document, $, undefined) {
...
}(window, document, jQuery);
));
The benefits of this are:
Privateness of variables in closure established by the anonymous function
Minor performance gains by making globals available as local variables in the closure
Ensures typeof(undefined) === 'undefined'
Independence of $ being tampered with by other scripts
Running this closure only when domready has fired
Benefits code compression tools by allowing globals to be referenced with shortened variable names. Think window > w
Yes, it won't conflict with other libraries.
Yes, it'l allow you to continue to use $ when another library overwrites it. However, your sample is a bit over-complicated; it can be simplified to:
jQuery(function($){
// code here
});
or
jQuery(document).ready(function($){
// code here
});
without losing any of the benefits.
He is using jQuery's $.noConflict() mode which frees up the $ for other libraries just as jQuery does, more info here.
Usually you would not need to do this unless you are using an additional library that is conflicting with jQuery. It can also be used to load 2 different version of jQuery.
This is not actually an "onload" function, but an "onready" function.
But if you mean whether to use jQuery instead of $, the benefit is definitely to prevent conflicts.
EDIT:
I think you may have mistyped the code. What you want to have is
(function($) {
$(function() {
// code here
});
})(jQuery);
This creates an anonymous function where $ is passed in as an argument so that any other global $ does not conflict. It then calls the anonymous function passing in jQuery as the $ parameter.

What does jQuery's $ mean in this function?

What is the difference in $?
Question:
What does $ mean in the next example?
JS:
jQuery(document).ready(function() {
console.log('loaded');
});
jQuery(document).ready(function($) {
console.log('loaded');
});
Can someone explain to me what is the difference between these 2 functions?
Thank you in advance
$ is normally the name of the jQuery constructor. That is to say, it is the name of a function that you call every time you want to make a jQuery object. For instance:
$('div')
It is normally a global variable, which means it is available throughout the page's Javascript. There is another variable jQuery, which normally points to exactly the same thing.
console.log($ === jQuery); // true
However, it is possible to set $ to something else. Perhaps you want to use $ to mean something different in your code. Or perhaps you're using Prototype as well, which also uses the $ symbol to point to a function.
This is why the jQuery.noConflict() method exists: it stops $ referring to jQuery.
However, many authors prefer to use $ to refer to the jQuery constructor, because it's much more concise and readable. jQuery provides a helpful feature that allows them to do this easily.
When you do jQuery(document).ready(function(), you are assigning an event handler. The function will be run when the event is fired. What we can do is reassign $ to refer to jQuery solely in the scope of that callback function. This is aided by jQuery: every $(document).ready callback function is called with the jQuery constructor as the first argument, so you can use whatever name you choose within the function.
For instance:
var $ = 'apples';
jQuery(document).ready(function() {
$('div'); // causes an error: "TypeError: string is not a function"
});
jQuery(document).ready(function($) {
$('div'); // works fine
});
This functionality is documented in the jQuery API for the ready method, in the section entitled "Aliasing the jQuery Namespace".
It's just the name of an argument.
See the documentation for ready:
the handler passed to the .ready() method can take an argument, which is passed the global jQuery object

Can someone explain what function($) does in jQuery

Recently I was reading someone else's code, and came across this:
// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {
// DOM Ready
$(function() {
...
});
})(jQuery);
I understand the point of the leading ;, And I understand that $(function() { is the same as document ready, but what is the point of adding function($)?
I understand it's a closure, but since this is always being called at the global scope, it seems like you don't need to bother with it. The $(function() { will use the same global object either way, no?
Is it to safeguard against something, or is it a best practice for another reason?
It's a common structure for a jQuery plugin. It safeguards against the $ identifier having been overwritten and used for something else. Inside the anonymous function, $ is always going to refer to jQuery.
Example:
$ = "oh no";
$(function() { //Big problem!
//DOM ready
});
By introducing a new scope, you can ensure that $ refers to what you expect it to:
$ = "oh no";
(function($) { //New scope, $ is redeclared and jQuery is assigned to it
$(function() { //No problem!
//DOM ready
});
}(jQuery));
The main reasoning behind this is that numerous other JavaScript libraries use $ as an identifier (e.g. PrototypeJS). If you wanted to use both Prototype and jQuery, you need to let Prototype have its $ identifier, but you probably don't want to write out jQuery every time you want to call a jQuery method. By introducing a new scope you allow jQuery to have its $ back in that execution context.
The code sample you've provided is an example of a Self-Invoking Function:
(function(){
// some code…
})();
The first set of parentheses defines a function: (an anonymous function wrapped in parentheses)
(function() {})
That defines the anonymous function. On its own, it doesn't do anything. But if you add a set of parentheses () after the definition, it's the same as the parentheses used to call a function.
Try this out:
(function(message) {
alert(message);
})("Hello World");
That creates a function which accepts a parameter, and displays an alert box containing the provided value. Then, it immediately calls that function with a parameter of "Hello World".
In your example, a self-invoking function is defined. It accepts a parameter, which is named $. Then, the function is immediately called, with a reference to jQuery being passed in as the argument.
This is common if you want jQuery to operate in noConflict() mode (which removes the global reference to $).
In noConflict() mode, you can still access jQuery via the jQuery global variable, but most people would rather use $, so this self-calling function accepts the global jQuery variable as a parameter named $ in the scope of the function, which leaves you free to use the $ shortcut within the self-invoking function while having jQuery operate in noConflict() mode to avoid clashes with other libraries that use $ in the global scope.
Hope this answers your question!

2 ways of writing jquery, what's the difference?

I have got a function, inside which are some simple expressions, adding nums, appending doms, etc.
Since I only have to call it once, so an anonymous function could do it. But which way should I choose and what's the difference?
1: Shorthand for $(document).ready() {}) I seen this a lot,
$(function(){
var something;
++something;
});
2: Found in jquery plugins. Is it binded to $(document).ready() too?
(function ($) {
var something;
++something;
})(jQuery);
The second one is not bound to the ready event.
In detail. This:
$(function(){ /* ... */ });
needs a variable $ defined. Usually this variable exists when jQuery is loaded and points to the jQuery function.
Subsequently, when you call the jQuery function with a function argument, jQuery is binding this function argument to the ready event. The above is equivalent to
jQuery(function(){ /* ... */ });
which is in turn a convenience shorthand for
jQuery(document).ready(function(){  /* ... */ });
Your second code snippet
(function ($) { /* ... */ })(jQuery);
does not rely on $ being defined or pointing to jQuery() (this can happen if multiple JS frameworks are loaded in parallel).
To still have the convenience of $ within a certain region of code, it creates a function within which $ is defined and points to jQuery(). However, it is not bound to a DOM event.
But this would be:
(function ($) {
$(function(){ /* ... */ });
})(jQuery);
This set-up is used to minimize the conflict between JS frameworks or other pieces of code that rely on $. jQuery plug-in authors use it to write plug-ins that work under many environments.
If you think the combined one is too complicated, jQuery also has a shorthand feature, which avoids variable conflicts and binds to document ready at the same time. But be careful, it only works on jQuery and has some downsides.
jQuery(function($) { /* some code that uses $ */ });
For more details, see these two articles:
Using jQuery with Other Libraries
.ready() # api.jquery.com (Aliasing the jQuery Namespace)
First
It's just shorthand
Second
You are sandboxing the use of $ to reduce conflicts with other libraries that use the $ shorthand.
$ is just a shortcut for the jQuery variable and is being passed into the inner function of the immediately invoked function...
Example
var outerVar = "something";
(function innerFunc(passedVar) {
passedVar === "something"; //true
})(outerVar);
innerFunc is executed and passed outerVar as its argument.
In your first example, the shorthand form is functionally identical to $(document).ready().
The second example is an immediately-invoked anonymous function (Thanks #Raynos for the correction: this is often called a self-invoking function; it is not one). The function is defined and executed in place, taking jQuery as its argument. One advantage of this approach is that variables declared within the function will not "pollute" the global (window) scope (as opposed, for example, to simply running that code outside the function). In your example, something is undefined outside the function.
Since jQuery is brought into the function as the argument $, $ is guaranteed to be jQuery within the body of that function -- even in cases where other libraries are using $ outside the function.
A useful side note: it's sometimes helpful to name "anonymous" functions. The, uh, functionality remains the same, but names can make it much easier to debug complex code.
(function superFunction (foo) { // naming this "superFunction"
var something = 10;
do_something_with( foo, something );
})(bar);
No it isn't, it is just a shorthand
No it isn't. This code makes sure that $ is really jQuery and not just another javascript library
From http://docs.jquery.com/Plugins/Authoring:
But wait! Where's my awesome dollar sign that I know and love? It's
still there, however to make sure that your plugin doesn't collide
with other libraries that might use the dollar sign, it's a best
practice to pass jQuery to a self executing function (closure) that
maps it to the dollar sign so it can't be overwritten by another
library in the scope of its execution.
Just combine the two styles.
jQuery(function($) {
// uses the real jQuery as $
// code
});
The first style was used to run some code when the DOM is ready.
The second style is used to ensure $ === jQuery and also to make $ a local variable (reduces lookup time by a tiny fraction)

What is this unknown JavaScript syntax?

Is this jQuery code
(function(jQuery){
})(jQuery);
equivalent to
$(document).ready(function () {
});
If yes, what are the differences between the two? If not, what does the first do?
EDIT:
Thanks everybody. Most response are similar with different flavours and sample
They are not equivalent.
Your first example is an Immediately-Invoked Function Expression (IIFE). It creates a closure around locally defined variables.
Your second example specifies a function to execute when the DOM is fully loaded. It is used to ensure that all element nodes in the DOM are available before executing the enclosed code. This is also a closure.
Both examples use anonymous functions.
It is worth pointing out that it is good practice to use both of your examples, like so:
(function($){
// locally-scoped, DOM-is-NOT-Ready-code here.
$(function () {
// your locally-scoped, DOM-is-ready-code here.
});
}(jQuery)); // note that I've moved the invocation into the parens
// that contain the function. This makes JSLint happy!
Absolutely not, the first one is a self-executing anonymous function and the second is the ready handler.
(function(jQuery){
//jQuery in this scope is referencing whatever is passed-in
})(jQuery);
So, the jQuery inside of the function isn't necessarily the same jQuery outside the function. But you typically do not want to mix-n-match global variable names with local ones.
Take this example:
(function(obj) {
alert(obj);
})('Hello');
This defines a function, then immediately invokes it, passing in "Hello"
$(document).ready(function () {
});
is equivalent to this:
$(function() {
});
The first snippet is an immediately invoked anonymous function which creates a local scope:
(function() {
var x = 2;
})();
alert(x); // undefined
No. The first one isn't really doing much. Just separating any variables inside from the surrounding scope, and creating a local jQuery variable inside.
The second one passes a function that is run after the DOM is ready (in other words after the <body> has loaded).
A common equivalent to:
$(document).ready(function () {
});
is:
$(function () {
});
which does the same thing.
While this:
(function(jQuery){
})(jQuery);
is often written as:
(function($){
})(jQuery);
so that the $ variable is no longer a global variable. Useful if the global $ variable is already in use.
Not at all. The first one is a closure - a function that you create and then immediately call. However, typically you would combine the two like this:
(function($) {
// use the $ variable
$(document).ready(function(){
// ...
});
})(jQuery);
By creating the closure you are renaming "jQuery" to "$" just locally for that block of code. The reason why you use the closure syntax is so that you can use the $ variable even though it might not be defined as a jQuery object in the global scope (i.e. some JavaScript frameworks like prototype use $ as a variable).
Whenever you write a jQuery plugin you should enclose all jQuery code in this kind of closure so it doesn't interfere with any other JavaScript frameworks. If you aren't writing plugins and you don't use any other JavaScript frameworks you probably don't have to bother enclosing your code in a closure.

Categories