How does JQuery utilize $ without a function by this name? - javascript

I'm currently learning JS and was dissecting the JQuery source code for practice.
I understand JQuery functions are accessible using the $ sign because $ is assigned to the main function used: JQuery(). However, when I comb through the source code, I cannot find a function named $ anywhere, and can only find function JQuery() or references to window.$. I realize JQuery utilizes JS's prototype function pretty extensively, so maybe that's why I'm not seeing it?
Can someone please point me to whichever line is making JQuery accessible via the dollar sign?
Thanks. I realize this is probably an amateur question.
Version of JQuery used: https://code.jquery.com/jquery-3.1.0.js

It's these lines:
if ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
In a browser environment, anything inside of window is global, so that's why $ is globally accessible.

$ is just a normal variable. You can do var $ = 12123
Something like ...
var $ = function () {
// some code
}

Related

jquery single variable declaration

I have a problem related to variable declaration. I use browserify, so here I have to require jquery before bootstrap.js. The issue is that I can't undestand what is the problem with the first variant of code?
var $, jQuery;
$ = jQuery = require('./libs/jquery/jquery.min');
require('./libs/bootstrap/bootstrap');
and
var $ = jQuery = require('./libs/jquery/jquery.min');
require('./libs/bootstrap/bootstrap');
First variant doesn't work (console shows me an error that bootstrap needs jquery), second variant is not good enough for Jshint but it works great! Can someone explain why the first variant doesn't work
Here's your answer:
Your first variant creates no global variables:
var $,jQuery
created two variables - $, and jQuery in the local scope.
The second one:
var $ = jQuery = ...
created one global variable jQuery and one local variable $. The first variant doesn't work because bootstrap is looking for the global variable jQuery and it can't find it.

What is the purpose of this? (function ($) { //function code here })(jQuery);

I am debugging someone else's JavaScript code and a majority of the code is wrapped like this:
(function ($) {
//majority of code here...
})(jQuery);
What is going on with the ($) and the (jQuery)? I wasn't taught to code like that and haven't seen them. What is their purpose?
As well, there is no document.ready, but I assume that is because the code is executed right after it's read by the (); at the end?
var $ = "some value we don't care about";
// v=====normal plain old function
(function ($) {
// ^=======receives jQuery object as the $ parameter
//majority of code here, where $ === jQuery...
$('.myclass').do().crazy().things();
})(jQuery);
// ^=======immediately invoked, and passed the jQuery object
// out here, $ is undisturbed
alert( $ ); // "some value we don't care about"
This is useful when you want / need to use jQuery.noConflict(), and the global name $ isn't an alias for jQuery. The code you posted lets you use the shorter $ to mean jQuery inside the anonymous function only, without $ needing to be a global.
Just to expand on RightSaidFred's answer a little, when I first saw the ()() syntax I was a bit befuddled, but it made sense once I realised the brackets are being used to define an anonymous function and then call it. e.g:
(function (msg){alert(msg)})('hello');
... defines a function and then calls it, passing 'hello' as a parameter.
So the example in the question:
(function ($) {
//majority of code here...
})(jQuery);
is passing jQuery into an anonymous function and referring to it as $ within the function, a way of guaranteeing that $ will work for jQuery without interfering with anything else.
This structure is called JQuery Plugin, purpose of the plugins is to create a framework of any common task/function in your project, same-way you can extend your plugins according to your usage in different page or in same page. that way you can avoid repeating the same code everywhere.
check it out http://docs.jquery.com/Plugins/Authoring

$(document).ready shorthand

Is the following shorthand for $(document).ready?
(function($){
//some code
})(jQuery);
I see this pattern used a lot, but I'm unable to find any reference to it. If it is shorthand for $(document).ready(), is there any particular reason it might not work? In my tests it seems to always fire before the ready event.
The shorthand is:
$(function() {
// Code here
});
The shorthand for $(document).ready(handler) is $(handler) (where handler is a function). See here.
The code in your question has nothing to do with .ready(). Rather, it is an immediately-invoked function expression (IIFE) with the jQuery object as its argument. Its purpose is to restrict the scope of at least the $ variable to its own block so it doesn't cause conflicts. You typically see the pattern used by jQuery plugins to ensure that $ == jQuery.
The correct shorthand is this:
$(function() {
// this behaves as if within document.ready
});
The code you posted…
(function($){
//some code
})(jQuery);
…creates an anonymous function and executes it immediately with jQuery being passed in as the arg $. All it effectively does is take the code inside the function and execute it like normal, since $ is already an alias for jQuery. :D
Even shorter variant is to use
$(()=>{
});
where $ stands for jQuery and ()=>{} is so called 'arrow function' that inherits this from the closure. (So that in this you'll probably have window instead of document.)
This is not a shorthand for $(document).ready().
The code you posted boxes the inside code and makes jQuery available as $ without polluting the global namespace. This can be used when you want to use both prototype and jQuery on one page.
Documented here: http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/#use-an-immediately-invoked-function-expression
The multi-framework safe shorthand for ready is:
jQuery(function($, undefined) {
// $ is guaranteed to be short for jQuery in this scope
// undefined is provided because it could have been overwritten elsewhere
});
This is because jQuery isn't the only framework that uses the $ and undefined variables
These specific lines are the usual wrapper for jQuery plugins:
"...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."
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
From http://docs.jquery.com/Plugins/Authoring
What about this?
(function($) {
$(function() {
// more code using $ as alias to jQuery
// will be fired when document is ready
});
})(jQuery);

I'd like to understand the jQuery plugin syntax

The jQuery site lists the basic plugin syntax for jQuery as this:
(function( $ ){
$.fn.myPlugin = function() {
// there's no need to do $(this) because
// "this" is already a jquery object
// $(this) would be the same as $($('#element'));
this.fadeIn('normal', function(){
// the this keyword is a DOM element
});
};
})( jQuery );
I'd just like to understand what is going on there from Javascript's point of view, because it doesn't look like it follows any syntax I've seen JS do before. So here's my list of questions:
If you replace function($)... with a variable, say "the_function", the syntax looks like this:
(the_function)( jQuery );
What is "( jQuery );" doing? Are the parenthesis around the_function really necessary? Why are they there? Is there another piece of code you can give that is similar?
It begins with function( $ ). So it's creating a function, that as far as I can tell will never be run, with the parameter of $, which is already defined? What is going on there?
Thanks for the help!
function(x){
x...
}
is just a function without a name, that takes one argument, "x", and does things with x.
Instead of 'x', which is a common variable name, you can use $, which is a less common variable name, but still legal.
function($){
$...
}
I'll put it in parentheses to make sure it parses as an expression:
(function($){
$....
})
To call a function, you put () after it with a list of arguments. For example, if we wanted to call this function passing in 3 for the value of $ we would do this:
(function($){
$...
})(3);
Just for kicks, let's call this function and pass in jQuery as a variable:
(function($){
$....
})(jQuery);
This creates a new function that takes one argument and then calls that function, passing in jQuery as the value.
WHY?
Because writing jQuery every time you want to do something with jQuery is tedious.
WHY NOT JUST WRITE $ = jQuery?
Because someone else might have defined $ to mean something else. This guarantees that any other meanings of $ are shadowed by this one.
(function( $ ){
})( 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.
If you even look at the source code of jQuery, you will see that everything is wrapped in between:
(function( window, undefined ) {
// jQuery code
})(window);
That is as can be seen also a self-executing anonymous function with arguments. A window (and undefined) argument is created and is mapped with global window object at the bottom (window). This is popular pattern these days and has little speed gain because here window is will be looked into from the argument rather than global window object which is mapped below.
The $.fn is jQuery's object where you create your new function (which is also an object) or the plugin itself so that jQuery wraps your plugin in its $.fn object and make it available.
Interestingly, I had answered similar question here:
JavaScript / jQuery closure function syntax
You can also check out this article to know more about self-executing functions that I had written:
Javascript Self-executing Functions
The basic plugin syntax allows you to use $ to refer to jQuery in the body of your plugin, regardless of the identify of $ at the time the plugin is loaded. This prevents naming conflicts with other libraries, most notably Prototype.
The syntax defines a function that accepts a parameter known as $ so you can refer to it as $ in the function body, and then immediately invokes that function, putting jQuery in as the argument.
This also helps not pollute the global namespace (so declaring var myvar = 123; in your plugin body won't suddenly define window.myvar), but the main ostensible purpose is to allow you to use $ where $ may have since been redefined.
You're dealing with a self-invoking anonymous function there. It's like "best practice" to wrap a jQuery plugin within such a function to make sure, that the $ sign is bound to the jQuery object.
Example:
(function(foo) {
alert(foo);
}('BAR'));
This would alert BAR when put into a <script> block. The parameter BAR is passed to the function which calls itself.
The same principle is happening in your code, the jQuery object is passed to the function, so $ will refer to the jQuery object for sure.
The jQuery at the end passes itself (jQuery) over to the function, so that you can use the $ symbol within your plugin. You ccould also do
(function(foo){
foo.fn.myPlugin = function() {
this.fadeIn('normal', function(){
});
};
})( jQuery );
To find a clear explanation of this and other modern javascript tricks and common practices, I recommend reading Javascript Garden.
http://bonsaiden.github.com/JavaScript-Garden/
It's especially useful, because many of these patterns are widely used in many libraries but not really explained.
The other answers here are great, but there is one important point that hasn't been addressed. You say:
So it's creating a function, that as far as I can tell will never be run, with the parameter of $, which is already defined?
There is no guarantee that the global variable $ is available. By default, jQuery creates two variables in the global scope: $ and jQuery (where the two are aliases for the same object). However, jQuery can also be run in noConflict mode:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery.noConflict();
</script>
When you call jQuery.noConflict(), the global variable $ is set back to whatever it was before the jQuery library was included. This allows jQuery to be used with other Javascript libraries that also use $ as a global variable.
If you wrote a plugin that relied on $ being an alias for jQuery, then your plugin would not work for users running in noConflict mode.
As others have already explained, the code you posted creates an anonymous function that is called immediately. The global variable jQuery is then passed in to this anonymous function, which is safely aliased as the local variable $ within the function.

I need a converter to make any jquery code to make no.conflict mode?

I need a converter to make any jquery code/plugin to make with no.conflict mode?
or it's just possible with find and replace.
As for the $ shortcut: if you place the code e.g. in a properly crafted anonymous function, you can still use it. Like:
(function ($, undefined) {
//Use $ shortcut for jQuery in this scope
$("input").val("clickme");
})(jQuery.noConflict());
The same works for the "extreme" variant of noConflict():
(function (jQuery, undefined) {
var $ = jQuery;
//Use jQuery and $ shortcut for jQuery in this scope
$("input").val("clickme");
})(jQuery.noConflict(true));
You would have to manually do this. There are no converters out there to do this automatically. The jQuery guide to authoring plugins specifically describes how plugins should bind to jQuery as opposed to the $ specifically to ensure they remain working if jQuery.noConflict() is called.
Basically it comes down to wrapping your code like this:
(function($) {
// jQuery can be used freely using
// the "$" within this code block
})(jQuery);
Keep in mind that this will remove any accidental (and some intentional) global variables from the global scope. To make variables global, assign them to the window object, like this:
(function($) {
var myGlobalObj = "hello world";
window.myGlobalObj = myGlobalObj;
// Now "myGlobalObj" can be accessed globally
})(jQuery);

Categories

Resources