Anonymous functions syntax in jQuery - javascript

I have read lots of articles regarding jQuery and its syntax. However I have not fully understood its syntax and I would really like to get a better and deeper understanding of it.
Many articles fail to point out the simple syntax rules (and what they are necessary for).
As of right now I am experiencing a syntax-understanding-problem:
my HTML:
<body>
jQuery.com
jQuery.com
jQuery.com
<!-- JQUERY -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
(function ($) {
// EXAMPLE 1
$("a").each(function () {
console.log(this.title);
});
})(jQuery); // ... everything works fine.
(function ($) {
// EXAMPLE 2
$("a").each(function () {
console.log(this.title);
});
}); // ... missing (jQuery). Why isn't this working?
$(function () { // ... notice the $ at the beginning.
// EXAMPLE 3
$("a").each(function () {
console.log(this.title);
});
}); // ... missing (jQuery). Why IS this working?
// EXAMPLE 4
$("a").each(function () {
console.log(this.title);
}); // ... everything works fine.
</script>
</body>
I will clarify how I understand the code, and I would absolutely appreciate if you answer me in a very basic manner. Please do point out all my misunderstandings!
My Understanding and Questions so far:
Example 1: I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it. I pass it the jQuery-Object (with ($) but I don't know why this is important at that point). From now on my function 'speaks' jQuery (it understands its syntax - I am assuming). At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.
Example 2: I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?
Example 3: Now I STARTED my Javascript-function with the $ and I assume that from now on my whole function is WRAPPED inside a jQuery object. Inside this jQuery-object my function understands jQuery syntax. At the end NO (jQuery) is needed.
Example 4: Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.
My Question basically is:
In Example 1, why is that ($) at the beginning AND the (jQuery) at the end necessary? What is the purpose?
I would really appreciate longer answers where I can get a deeper understanding of "reading jQuery syntax correctly" and speaking about jQuery syntax and what it requires. Thanks.

I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it.
Not quite. You create a function expression.
function () { }
You then follow it with () which calls it a moment later.
You could have done it like this:
var myfunction = function ($) { ... };
myfunction(jQuery);
I pass it the jQuery-Object (with ($) but I don't know why this is important at that point).
No. You are defining a function. It accepts a single argument, the value of which gets assigned to a local variable called $.
From now on my function 'speaks' jQuery (it understands its syntax - I am assuming).
Syntax belongs to JavaScript, not jQuery.
At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.
You are passing the jQuery object for the first time. It is the argument you are passing to the function when you call it. The value of jQuery (the jQuery object) is assigned to the local $ variable.
This is used for two purposes:
It lets you use the $ variable without worrying about it being overwritten by Prototype JS, Mootools, or any of the other libraries that thought it was a good idea to use something as generic as $ as a variable name.
It lets you have local variables that won't pollute the global scope.
I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?
The () are important because without them you won't call the function.
The jQuery is important because otherwise $ would be undefined within the function.
Now I STARTED my Javascript-function with the $
Here you are calling the function $() with your function expression as the argument.
$ is a horribly overloaded function that does many different things depending on what type of argument you pass it.
If you pass it a function, then it will assign that function as a document ready event handler.
When the DOM has finished loading, the event will fire and the function will be called.
Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.
Yes

First off, there is no "jQuery syntax". jQuery is a library, written in JavaScript, so the syntax is JavaScript.
Example 1: I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it. I pass it the jQuery-Object (with ($) but I don't know why this is important at that point). From now on my function 'speaks' jQuery (it understands its syntax - I am assuming). At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.
You seem to know how functions and arguments work. So look at your code:
(function ($) {
// EXAMPLE 1
$("a").each(function () {
console.log(this.title);
});
})(jQuery);
You define an anonymous function that takes one argument: a variable named $, which you use in the statement $("a"). Then you call your anonymous function and pass it the jQuery object, so inside the function, $ === jQuery.
Example 2: I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?
Without the () at the end, you're not even calling your function. You just define it and then lose it since you're not assigning it to a variable.
If you put just (), it won't work either because the function argument $ would be undefined and override the global $ (window.$).
However, if you declared the function just as function(), I think it would work because $ would then refer to window.$.
Example 3: Now I STARTED my Javascript-function with the $ and I assume that from now on my whole function is WRAPPED inside a jQuery object. Inside this jQuery-object my function understands jQuery syntax. At the end NO (jQuery) is needed.
Now you call $ as a function with one argument: your anonymous function.
Example 4: Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.
Yes you do build a function, and you pass it as argument to the each() function of the object that $("a") returns.
My Question basically is:
In Example 1, why is that ($) at the beginning AND the (jQuery) at the end necessary? What is the purpose?
What's the purpose of arguments to functions?
But what you don't seem to understand: $ is just a variable (or a function if you want, but in JS functions are variables).

The solution to your problem comes down to understanding closures within JavaScript ... and not so much jQuery - jQuery is just using closures.
With a closure you can scope the content that is within and also pass arguments to that closure for use within.
For your example 2, if you pass in jQuery to the closure it would work fine.
Like:
(function ($)
{
$("a").each(function () {
console.log(this.title);
});
})(jQuery); // arguments passed in here
Becuase you do not pass in jQuery at the end then the argument $ is undefined and therefore cannot be called in the case of $('a'). When written the way I have changed it jQuery is assigned to the $ argument, which is available to the code which is inside the closure.
Similarly for your example 3, you are not passing in jQuery and you also have no variable $ within your closure so it will not work. Note that you could change it to be like (illustrative purposes only):
(function (thisIsJquery)
{
thisIsJquery("a").each(function () {
console.log(this.title);
});
})(jQuery);
Now jQuery is assigned to the argument thisIsJquery and it is available within the closure.
As for your exmaple 4, $ is being used within the closure it was defined in (and not another closure inside that) so it is readily available for use.
Closures are an excellent way to hide implementation and provide a way to make things private in JavaScript.
Further reading:
http://www.w3schools.com/js/js_function_closures.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

I'll only focus on what's not working. The following snippet:
(function ($) {
$("a").each(function () {
console.log(this.title);
});
}) // not calling function
First of all, you're not calling the function. So, anything inside it will not run. So, you might think that by adding () at last, might solve it.
But that's not all!
Because $ refers to jQuery, outside the snippet. But since you're including a named parameter as $ and not passing anything to it, the $ inside the snippet shadows the one outside. And since it's not assigned any value, it is undefined. So you'll end up with
undefined is not a function
To prove it, adding ($) will work, as now, the named parameter $ refers to the $ which points to jQuery.

Related

Jquery function?

Before writing any jquery they always recommend us using
$( document ).ready(function() {});
and place all our code within this function, but I noticed certain tutorial use this instead
(function($){})(jQuery)
and
(function($){}(jQuery));
what is the difference actually?
$( document ).ready(function() { YOUR CODE });
1. This code wraps YOUR CODE in jQuery's on document ready handler. This makes sure all the HTML is loaded before you start running your script. Also, since YOUR CODE is part of an anonymous function (a closure), this keeps your global scope clean.
...
$(function(){ YOUR CODE });
2. This is the same thing as #1, just using shorthand.
...
(function($){ YOUR CODE })(jQuery)
3. This does not wrap anything in an on ready handler, so it'll run immediately, without regard to what HTML has been loaded so far. However, it does wrap YOUR CODE in an anonymous function, where you'll be able to reference the jQuery object with $.
...
(function($){ YOUR CODE }(jQuery));
4. This is the same thing as #3.
$(document).ready(function() {//when document is read
And
$(function() {
are the same thing, the second is just short hand
You can also do
$(window).load(function() {
//The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images.
(function($){})(jQuery)
is an Self-Executing Anonymous Function
So basically it’s an anonymous function that lets jQuery play nicely with other javascript libraries that might have $ variable/function. Also if you notice, all jQuery plugins code is wrapped in this anonymous function.
The first one is executing the function as soon as the document is ready while the others are IIFE's that ensures jQuery can be accessed via it's alias sign $ within that function :
var $ = 'other plugin';
(function($){
alert($); // jQuery here
})(jQuery);
The first one makes the method run on document ready. Read more here.
(function($){/*Your code*/})(jQuery)
The last two encapsulate variable / function declarations in your code to a local scope, that gets as a prameter the jQuery object. This approach is used for not littering the global scope with declarations,ie localizing variables.
The difference between the last two is just that the first one delimits function with an extra set of parentheses, to make it visually more clear.
Basically this is how modules are constructed in javascript and making sure one block of code doesn't affect the other.
For more information here's a good article about js development patterns.
Example:
var f = function (str) {
window.alert(str);
};
var name = "John Doe";
f();
Functionally is the same as
(function (w) {
var f = function (str) {
w.alert(str);
};
var name = "John Doe";
f();
})(window);
And as you can see, the first one creates variables in the global scope, that might affect other scripts, while the second one does everything locally.
Moreover in the second example I did rename the reference to window, and made it available for the method through w. The same happens in your example as well.
Imagine having two js libraries that both use the alias shorthand $. You wouldn't know in your code where, which gets referenced. While on the other hand jQuery always references the jQuery library. And in your case the last two methods just make sure that $ is just a renamed jQuery object, and not anything else coming from another library.

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

jQuery Selector Before Function

what is the difference between:
$(function () {
});
and this:
function HideDiv() {
}
i know first is jQuery Function and second is Javascript function.
but i don't know why it putted selector '$' before Function Keyword .
i thought that jQuery Selector is for finding an html Element for example this:
$("#loading").hide('fade');
finding an element with the name loading and hide that.
regards.
The $ is shorthand for jQuery, and represents the jQuery object. That context is basically a shorthand of:
jQuery(document).ready(function()
{
});
and acts as an onDOMReady function for executing code when the page has loaded. You are fundamentally "finding" the document element and running a script when it has finished loading.
The second one is just a general function
The difference is very large!
function HideDive(){
}
Creates a named function which you can later call as: HideDiv
$(function() {
});
Does something entirely other: it registers an anonymous function with jQuery, essentially saying: when the page is done loading, please call this function.
The $( ... ); notation is a shorthand which means jQuery(document).ready( ... ).
Hope this clears it up!
There are functions involved in both of those, but the context is a little different. The first:
$(function() { ... });
is both a function call and a function definition. The call is to the jQuery function itself, whose alias is "$". The function call has a parameter, and that parameter is an anonymous function. The jQuery function will respond to this function call by saving a reference to the anonymous function, and then — when the document is ready — it will call your function.
The second form is just a simple JavaScript function definition statement. It creates a function with a name that can be called by other code in the same scope, or in any lexically-enclosed scope.
The former is an anonymous function that is invoked when the DOM is ready to be interacted with by jQuery. It is analagous to:
$(document).ready(function() {
// ...
});
The latter is a named function which can be called by any code within it's scope.
Another interesting piece of function syntax is:
(function() {
// ...
})();
which is a self-executing function.
The first function (the "jQuery function") is, technically, still a JavaScript function as jQuery is just a JavaScript library. However, in this specific case, this function means something special to jQuery. Specifically, it is the ready function meaning that it will run after the DOM is ready (AKA, the page has loaded).
The second function is a "regular" function. This can be called from other portions of JavaScript code (including jQuery code, which, if you recall, is JavaScript). This allows you to encapsulate various actions or pieces of information that you may use repeatedly (rather than repeating over and over). You can combine the two, as well, like this:
$(function() {
// Call the function...
MyFunctionToDoSomething();
});
function MyFunctionToDoSomething() {
// Do stuff here.
}
The first is shorthand for $(document).ready(function(){}) [though doesn't work in after 1.4 I believe]. I can see it being easily confused with an anonymous function either way based on syntax.
A typical anonymous function would look just like your first example without the $. See Why do you need to invoke an anonymous function on the same line? for how the anonymous function works.
The second is a standard JS function (which is also an instantiatable object).

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.

Need some help understanding this JavaScript

I have the following strange looking code in a js file and i need some help in understanding whats going on. What im confused about is why is the whole thing put in paranthesis ?. What does that mean ?
(function() {
var someobj = window.someobj = [];
var parentId = '#wrapper';
$(document).ready(function() {
//some code here
});
$(document).ready(function() {
//some code here
}
});
If the code that you provided is complete (with the exception of what is inside the two $(document).ready(function() {}); statements), than this code does nothing and the function is never executed. It's the same with or without the wrapping parenthesis.
By wrapping a function in parenthesis, you can create an anonymous function. However, the function must be executed immediately, or stored in a variable (which would negate the anonymous part). You'll often see this technique to avoid polluting the global scope with variables that are temporary or only used for initialization of a larger application. For example.
(function() {
// Do initialization shtuff
var someLocalVariable = 'value';
})();
// Notice the `();` here after the closing parenthesis.
// This executes the anonymous function.
// This will cause an error since `someLocalVariable` is not
// available in this scope
console.log(someLocalVariable);
So then, what your code is missing is the (); after the closing parenthesis at the end of the function. Here is what your code should (presumably) look like:
(function() {
var someobj = window.someobj = [];
var parentId = '#wrapper';
$(document).ready(function() {
//some code here
});
$(document).ready(function() {
//some code here
});
})();
It does not look like this code is complete. As written, this code will do nothing at all. Are you missing a close paren and an extra set of parentheses at the end?
In JavaScript, there is no module system, and thus no way to create a module with its own top-level definitions that don't conflict with other modules that might be used.
In order to overcome this, people use anonymous function definitions to avoid name conflicts. What you do is create an anonymous function, and execute it immediately.
(function () { /* do stuff */ })();
This creates a function, and then executes it immediately with no arguments. Variables defined using var within that function will not conflict with variables defined anywhere else, and thus you get the equivalent of your own, private namespace, like what a module system would provide.
The outer parentheses are redundant here (there is a typo in your code though, I think you're missing the closing );). Sometimes people will wrap a function in parentheses for clarity when invoking the function immediately, e.g.
(function($) {
//some jQuery code
})(jQuery);
Within the function above, the parameter $ will have the value of the outer jQuery variable. This is done within jQuery and jQuery plugins to prevent the $ symbol clashing with other frameworks.
I'm going to assume that this is actually part of an anonymous function definition and that's why it's in parenthesis. I could see doing this if there was some sort of logic going to make window.someobj change based on different conditions, but have code further along do the same thing.
The parenthesis aren't actually necessary as far that this code goes. This code doesn't seem complete though. The function initializes by setting a variable to some object on the page and then setting another constant. Then there are two seemingly identical triggers that will trigger some code on page load.
Doesn't seem like a very useful piece of code. Is there some larger portion that might shed some light on this?
In JS, You can declare a function and automatically call it afterwards:
( function Test() { alert('test'); } )();
The parentheses define a temporary scope. It is sometimes useful to do so in JavaScript. There are a number of examples and further explanation in John Resig's excellent guide to learning advanced JavaScript:
http://ejohn.org/apps/learn/#57

Categories

Resources