jQuery difference between argument and parameter - javascript

I have jQuery code block as follows;
(function($){
//Normal code goes here
})(jQuery);
Now I wanted to understand
If this is a self-executing function ? If yes, why ?
What is the difference between the "$" passed to the function and "jQuery" specified at the end ? Is one of them called an argument and the other parameter ?
Is it necessary to specify the "jQuery" at the end.
Thank you.

If this is a self-executing function ? If yes, why ?
Yes and no. It is an Immediately-Invoked Function Expression, but some people tend to call these "self-executing" even though this is usually associated with the idea of recursion.
What is the difference between the "$" passed to the function and "jQuery" specified at the end ? Is one of them called an argument and the other parameter ?
Exactly.
Is it necessary to specify the "jQuery" at the end.
Otherwise from where the $ parameter would be populated?
I'll add one more question which you seem have to have missed:
Why use an Immediately-Invoked Function Expression?
It simply aliases jQuery to $ inside the IIFE scope so you can safely use $ independently of jQuery being in noConflict mode or not. Very useful for developing plugins and working with WP.

Yes, it's "self executing". The inner part is a "function expression" and the (necessary) parameters (jQuery) then cause it to be immediately invoked, hence the more usual term of "immediately invoked function expression".
The variable $ is local in scope to the function. jQuery plugins are often written this way so that the common $ abbreviation may be used internally even if jQuery is in "no-conflict" mode, because the (global) $ variable is being used by something else.
Formally the variables in the declaration are called the "parameters" and the ones in the invocation are the "arguments". I think in JS the ambiguity arises because you can access the supplied parameters using the arguments pseudo array.

1) Self-Executing and Immediately-Executing
You can tell because it's got the parens at the end.
You write a function like this:
function myFunc () {}
or like
var myFunc = function () {};
And you call a function like:
myFunc();
You have it written as (function () {})(); so it fires as soon as it hits the end.
2) Parameters are what a function expects.
Arguments are what you give a function.
var number_arg = 35,
string_arg = "Bob";
function myFunc (number_param, string_param) {
console.log(number_param, string_param);
}
myFunc(number_arg, string_arg); // 35 "Bob";
The fact that params can be named differently from arguments means that you can "alias" values differently inside of functions.
function myFunc ($) { console.log($); }
myFunc("SUPERLONGSTRINGOFDOOMISWHATI'MPUTTINGINHERE");
myFunc(MYAPP.Module.sub_module.plug_in);
Meanwhile, inside the function, all of these things can be worked with, just using $.
3) "Aliasing" is what's going on with the jQuery versus $.

Related

function call with '$' as parameter

I have a script which contains the following piece of code:
(function ($) {
// ...
})($);
Can anyone explain how to read it?
Create an anonymous function
Let it take one argument which will be called $
Call the function immediately
Pass it one argument which is whatever the value of $ is in the outer scope.
If the $ in the outer scope changes (by having a new value assign to it) then the value for $ in the inner scope will be protected from the change (since it is a different variable).
This also provides a clean scope for all other variables declared inside the function (if they use var as they should).
'$' is a legal variable in JavaScript. It could have just as easily been someCrazyLongVariableName
It kind of defeats the purpose of encapsulating the $ sign into an anonymous function.
It's a self executing anonymous function that takes $ as argument.
In most of the cases, you use this markup to avoid js libraries collisions : say that you want to use jQuery and prototype in your project. Very nice, but they both use the '$' sign... how to overcome this?
// jquery code here
(function($){
alert($ === jQuery);// the $ is a shortcut to jQuery
})(jQuery);
// non-jquery code here - ex: prototype
alert($ === jQuery);// the $ is NOT a shortcut to jQuery ANYMORE
If you're not thinking about the $ in particular, the extract is creating a javascript function and calling it in a single statement.
I'm not 100% sure, but i guess that the 2 $ variables would be a different scope.
I found this page useful, if a little verbose: -
http://www.authenticsociety.com/blog/JavaScript_DollarSign
In summary, it's no different to calling the variable a, but should be avoided.

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.

How do jQuery's namespaces work? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What does this JavaScript/jQuery syntax mean?
I specifically mean when you do this:
(function ($) {
...
})(jQuery);
I've never seen that kind of syntax before. How does the function get called? I understand when you do it like this:
jQuery(function ($) {
...
});
because the function is being passed to jQuery, and jQuery can just run any function passed as a parameter when the DOM's ready, but the first one's different.
Duplicate of What does this JavaScript/jQuery syntax mean?
I'll post my answer here, though seeing as Jeff Attwood seems to want us to embrace duplication: (https://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/)
This convention is used when writing plugins to ensure there is no confilict with other Javascript libraries using the $ notation, whilst ensuring the plugin author can still use this notataion:
(function($){
...
})(jQuery);
The author is declaring an anonymous function with a single parameter ($), then immediately calling it and passing the jQuery object to it. This ensures the function is called and that everything in it is defined.
A longer notation might be:
function MyDefs($){
...
}
MyDefs(jQuery);
Although that would create a variable MyDefs in the global namespace. The anonymous function pattern leaves the global namespace empty, avoiding conflicts.
It's an anonymous function. When you write:
(function ($){
..
})(jQuery);
It is mostly equivalent to:
function the_function($) {
..
}
the_function(jQuery);
The only difference being that the first does not create a function called the_function and therefore created no risk of accidentally overwriting an existing function or variable with that name. And of course, all of it is equivalent to:
function the_function() {
var $ = jQuery;
..
}
the_function();
The point of this construct is that any variables defined inside the_function are local and therefore cannot accidentally overwrite any variables or functions in the global scope. For instance, the code inside the function uses $ to represent the jQuery object, but this would conflict with other libraries that use $ as well (such as Prototype). By wrapping the usage of $ inside a function, the Prototype code outside the function remains unaffected.

In Javascript, what does this syntax mean?

I found this snippet when i was looking at jQuery plugins and wonder what it actually does
A jQuery plugin skeleton:
(function($) {
...
})(jQuery);
And more recently in nettuts:
var STICKIES = (function () {
...
}());
This creates a anonymous function and calls it directly:
this is equivalent to
var fun = function(){};
fun();
its used in jquery plugins to ensure compatibility with other libraries defining a global variable '$'. in your plugin sekeleton, you wrap your plugin in a anonymous function, which receives an argument named '$' (thus overriding a global variable '$'), this anonymous function is then called with 'jQuery' as parameter, so effectively $ becomes = jQuery, but only within that anonymous function.
The first part:
function($) {
...
}
creates an anonymous function.
The second part: wrapping this function with braces and (jQuery); cal the function with jQuery as argument (usable via $ in the function).
nettuts then saves the result of the call in the variable.
The first function means that $ is overwritten by jQuery, which is useful if
you have given a different meaning to '$' in the script.

a simple question on jquery closure

what does this mean?
(function($){
})(jQuery);
to make the question clearer, what does wrapping a function in parenthesis mean in JS (sorry, I'm a bit confused on the concept of closures). What about the $ parameter? and the "jQuery" in the end parenthesis?
Can I do the same with mootools and combine them in 1 JS file?
(function($){})(jQuery);
(function($){})(mooTools);
I have only worked with jquery and am planning to work with Mootools
Wrapping a function between parenthesis ensures this function to be evaluated as a function expression.
That happens because the Grouping Operator (the parentheses), can only evaluate expressions.
If no parenthesis are used, it will be interpreted as a function declaration, and it will cause a syntax error, since the function name is not optional for function declarations.
(function(arg){
alert(arg); // alerts test
})("test");
In the above example, the function expression is automatically executed, passing an argument.
That pattern is heavily used by jQuery plugins, since jQuery can run in noConflict mode, the $ global variable will not be created, so the jQuery global object is passed as an argument of this anonymous function and inside of that function, you can freely refer to it as $ (the received argument).
Keep in mind that also, the function context (the this keyword) inside self-executing function expressions invoked like the above example, will refer always to the Global object.
For a more in-depth info about the differences between function expressions and function declarations, give a look to the following resources:
Explain JavaScript’s encapsulated anonymous function syntax
Named function expressions demystified
CMS have given you the correct answer but I just want to add that this is not a closure. This is just the () operator being used to return the result of an expression which in this case is a function expression and the fact that in javascript, a returned anonymous function can be called directly. So this is simply combining both:
var x = (1+1); // <-- () evaluates an expression
and:
var arr = [0,1,2];
arr.push(function(text){alert(text)});
arr[3]('hello'); // <-- function returned by array called directly
And as for the $ parameter, that's just one of the characters that javascript allows for variable names. Your examples is exactly equivalent to:
(function(jQ){})(jQuery);
(function(moo){})(mooTools);
The main point for doing this is so that objects created within the function's expression can be utilized from properties and methods attached to passed in objects, without exposing those objects publicly. This can aid in preventing variable collisions. It also allows for variables created to be accessed as private storage for anything that is attached..
(function($){
//jQuery is available here as $
var myPrivateArray = []; //this is private
$.addItem = function(item) {
myPrivateArray.push(item);
}
})(jQuery);
//I can't access myPrivateArray here...
//but I can use jQuery.addItem to add something.
Here is an article on closures: http://www.jibbering.com/faq/faq_notes/closures.html
Basically, as CMS has said, it is a function expression. There is a perfect example to help you better understand about 2/3 of the way down that page.
The jQuery in the last set of parentheses means you're passing the jQuery object to the inner function. That inner function takes the object and it is assigned as $. So, when you're accessing the $ inside the function, you're actually acting upon the jQuery object you've passed.
As for mixing these with jQuery and Mootools, I've never used Mootools so I'm not sure how it assigns itself. The only thing I would think is that if it uses $ like jQuery, you can call jQuery.noConflict(); and reassign jQuery to another variable, maybe var $j = jQuery; Then, you can use Mootools as you normally would.
function($) { ... } creates a function that accepts a parameter called $.
Wrapping in in parentheses does nothing.
Adding (jQuery) calls the function with jQuery as a parameter.
This is done to make the function independent of $ in the global scope.
When you write $ in the function, you're referring to the parameter $, not the global variable $.
the mootools equivalent for namespacing $ is:
(function($) {
// $ is the mootools one (aliasing document.id)
})(document.id);
you can combine them into one file, but keep in mind that mootools is a prototypical framework and $ only serves the purpose of a selector whereas all functions go into the element/array/class etc prototypes. hence doing this in mootools works:
var foo = $("bar");
foo.hide(); // the element inherits .hide()
but in jquery it will fail and needs to be transcribed as
var foo = $("#bar");
$(foo).hide();
the point is, you can't namespace the stuff that mootools exports into prototypes.

Categories

Resources