Why should I reference jQuery in a self contained function? - javascript

(function ($, undefined) {
. . .
})(jQuery);
I see this everywhere, but I don't understand why we're sending jQuery as a parameter in a self contained function. jQuery is already being referenced. Also, why are we defining undefined as a parameter?

Passing $ to the anonymous function ensures that the namespace is protected (i.e. does not conflict with other libraries that also use the $ shortcut).
Oftentimes, undefined is passed to a function to ensure that the variable is truly undefined. For example, consider the following code exerpt:
undefined = '123';
if(myVar == undefined)
{
// Will only ever execute if myVar == '123'
}
As noted in the comments though, unless you're writing a plugin or some such, using jQuery(function($) { }) is probably a better approach, since it protects the $ shortcut and also provides a DOMReady event, meaning less code is required to achieve the same result.
If you need to check against undefined, you might also want to consider using $.noop().

It's possible that $ or undefined might have their values changed by subsequent code, eg. if you're mixing multiple JS libraries, or using multiple versions of a library. By capturing your own copy of $ and undefined, you guard against that.

(function ($, undefined) {
. . .
})(jQuery);
with that you'll be sure that $ is jQuery inside the function(whatever jQuery is in your script).
It doesnt prevent you from overwriting jQuery variable though,so use it only if you really need it( or you are creating a plugin and distributing a jquery plugin).
As for undefined,it will force undefined to actually be undefined,as undefined can be overwritten in some js engines.

Related

Can we replace $ in prototype.js with some thing else like $p or $proto

I am using jquery and prototype.js. There is conflict in $.It could be resolved by using var $j = jQuery.noConflict(), but i have a plenty of file that are using $ for jquery so that would not be easy to remove. even i am using some plugings that also needs to be rename.(like jquery.dataTables.bootstrap.js in which i have to change from $ to $j)
So my question is can we rename $ in prototype.js to something else, so it will be easy.I am using prototype of version 1.5.1.
Thanks
Simple answer, no - the some of the PrototypeJS modules (Array, Enumerable, RegExp, String, etc) depend on the $() function being available, and expect it to return an extended element instead of a jQuery collection.
However you can wrap the jQuery code in a immediately executed function to work around your problem.
for example
(function($){
//jQuery code in here that uses $()
})(jQuery);
This is basically a Javascript closure that renames the jQuery() method to $() inside that context
changing $ to $p causing some problem(like calling jquery hide or show function, prototype.js function gets called). So i what did to solve the conflict is to open a prototype.js related things in new tab and using jquery.noConflict().

What exactly does !function ($){...}(window.jQuery) do?

I'd like to know exactly what's going on here. I know what $(document).ready(function() {...}); does and when it comes into effect. Same goes for jQuery(function($) {...}.
But what does this do?
!function ($) {
$(function(){
var $window = $(window)
//normal jquery stuff
})
}(window.jQuery)
Is it loaded when jQuery is loaded instead of when the document is 'ready'?
It creates a closure in which the variable $ is assigned the value of window.jQuery.
The intention is to allow the uninformatively named variable $ to be used as a shortcut for jQuery without conflicting with the large number of other libraries and custom functions that also use $ as a variable name.
Using the ! operator before the function causes it to be treated as an expression
!function () {}()
The syntax you're looking at is used for setting up a jQuery closure. This is used to ensure that the jQuery $ variable is garuanteed to be available and correct within the code; ie it can't be overwritten in the global scope by anything else (which is possible if you're using multiple libraries, etc).
This technique is often used by jQuery plugin authors -- if you're interested in finding out more, the docs are here, and explain in more detail why you'd want to wrap your jQuery code in a function like this.
The only point of interest that's different in your example is that in the docs, the function is wrapped in brackets, whereas in the example you've given it's preceded by a !
The ! is a not operator, but doesn't actually get used for anything; I think it's just there instead of the brackets to save a single character of code. Probably helpful if you're into minifying javascript.
Not quite sure but I guess this is somewhat equivalent to (function(){})() approach and it's about js closures. And it ensures $ and jQuery are the same thing
The '!' is a 'not' operator. It doesn't do anything in the code. The only reason it is there is to signify that the function will execute immediately.
You may also see functions wrapped in parenthesis instead.
(function() {}());
Whatever is used is personal preference.

Please explain these lines in the jQuery-ui project - has to do with adding "sub-plugins"

Lines 10 - 16 of jquery.effects.core.js:
;jQuery.effects || (function($, undefined) {
var backCompat = $.uiBackCompat !== false; // Irrelevant
$.effects = {
effect: {}
};
})(jQuery); // At end of file
As I understand it, this adds an effects "namespace", but only if it doesn't already exist.
Can someone explain to me:
What is the initial semi-colon for?
What is the purpose of the undefined parameter? Is the meaning of undefined overridden in some way?
What's the difference between adding a function directly to the jQuery object, and adding one to jQuery.fn as recommended in the jQuery documentation?
Finally, if I wanted to create a bunch of jQuery plugins that would only be used by my own team, would it make sense to lump them all under a company namespace using something like the code above?
Edit: I realize now jQuery.effects is probably a bad example. I see jQuery.ui.core.js does it differently:
(function( $, undefined ) {
$.ui = $.ui || {};
// add some stuff to $.ui here
$.fn.extend({
// plugins go here
});
})(jQuery);
But what is the use of the ui object if plugins are added directly to $.fn anyway? Could I define my namespace under $.fn and add all my plugins to $.fn.acme, so that I use them like so: $('something').acme.doStuff()?
Is there a best practice for this sort of thing?
It checks if jQuery.effects exists
If not, it defines a function and calls in the same time
(function() { ... } (jquery), it passes jQuery object for reasons related to scope and conflict and such.
The first line in that function is said to be irrelevant, it seems to be checking a presence of a jQuery plugin property
It defines a placeholder (like namespace or container class) for the effects jQuery plugin property.
So, to your questions:
1 . What is the initial semi-colon for?
I think nothing special. Just ensuring clean statement. This has some edge cases if the last line before this one was a function declaration close.
2 . What is the purpose of the undefined parameter? Is the meaning of undefined overridden in some way?
It just ensures this doesn't happen later. Passes the global object directly. Common pattern I think.
3 . What's the difference between adding a function directly to the jQuery object, and adding one to jQuery.fn as recommended in the jQuery documentation?
It's the way jQuery is structured and general organization issue. The jQuery object is a function and returns an object. The .fn handles registering this one to apply on returned jQuery objects (from jQuery select or so), so, that's better so that jQuery actually knows about your added function.
4 . Finally, if I wanted to create a bunch of jQuery plugins that would only be used by my own team, would it make sense to lump them all under a company namespace using something like the code above?
Most people don't do it. Wouldn't recommend it. Maybe a common "small" prefix is enough.

What object does the $ sign in "function loadGal($) "?

I have a gallery that I am trying to integrate in my site. I am replacing a and then I want to call the galleries function "function loadGal($)" so the gallery will be rebuilt. But I don't know what kind of parameter to send to it.
Before I changed it, it was called inside "jQuery(document).ready(function($) {"
I just tried to do something like this:
jQuery(document).ready(function($) {
loadGal($);
});
it works fine but I don't know what is the dollar...
The $ is just the name of the parameter. It is nothing special. $ is a valid character of variable names in JavaScript.
However it is often used by libraries such as jQuery or Prototype as it is probably the most characteristic one-letter variable (j or p don't stand out that much) (meaning it is easy to spot and easy to use as you only have to type one character).
The value passed to the ready handler, is the jQuery object (emphasis is mine):
When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code
but you can name the parameter however you want. You could also write:
jQuery(document).ready(function(foobar) {
loadGal(foobar);
});
Update: And now that I understood the real question ;)
$ is the jQuery object, so you can write:
loadGal(jQuery);
But note that loadGal might not work if it has to work on the DOM elements and you call it outside the ready handler.

Weird syntax for extending jQuery

I recently saw this code on another post ( jQuery Set Cursor Position in Text Area )
new function($) {
$.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
}
} (jQuery);
After too long trying to understand what it was doing I finally figured out that it's just creating a new function with a parameter $ and then invoking it with jQuery as the parameter value.
So actually, it's just doing this:
jQuery.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
}
What's the reason for the original, more confusing version?
For large blocks of code using $ is much nicer than jQuery.
When using multiple libraries, people will often disable the $ shortcut because many libraries use it. Writing the code like that allows users to write code with the shortcut without worrying about conflicting with other libraries. And since this site applies to a wide audience, using that code is the most likely to work whether or not the user has $ enabled.
Since other JavaScript libraries may use $ globally, your library should explicitly reference jQuery to prevent conflicts. By creating a function with parameter $, you can bind the jQuery object to that variable within the scope of that function. This gives you the safety of explicitly specifying the jQuery object AND the convenience of using the $ shorthand.
This is the pattern I am used to seeing:
(function($) {
// code using $ goes here
})(jQuery);
new function($) {
$.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
// You are safe to always use $ here
}
} (jQuery);
and
jQuery.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
// you have to make sure $ was not overwritten before using it here..
}

Categories

Resources