stylesenberg
stylesenberg

Reputation: 519

Anonymous functions syntax in jQuery

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>
    <a href="http://www.jquery.com" title="anchor1">jQuery.com</a>
    <a href="http://www.jquery.com" title="anchor2">jQuery.com</a>
    <a href="http://www.jquery.com" title="anchor3">jQuery.com</a>

    <!-- 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.

Upvotes: 5

Views: 9694

Answers (4)

Amit Joki
Amit Joki

Reputation: 59292

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.

Upvotes: 3

Quentin
Quentin

Reputation: 944451

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:

  1. 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.
  2. 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


Upvotes: 9

Siguza
Siguza

Reputation: 23890

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?

  1. 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.
  2. 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).

Upvotes: 6

click2install
click2install

Reputation: 998

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

Upvotes: 5

Related Questions