JavaScript basics

Possible duplicate:
$ (document) .ready shortorth

Can someone help me understand the JS code below please:

$(function(){  <-- Is this a JS constructor? Why we need this?
    var someVariable = $(".classa").on('click', function() { <-- At what point in time does someVariable get populated?
        var $this = $(this);
            id = $this.attr('id');
         someVariable.removeClass('selected'); 
    });

    var someVariable2 = $(".classb").on('click', function() {
        var $this = $(this);
            id = $this.attr('id');
         someVariable2.removeClass('selected');
    });
});
+3
source share
2 answers

$is the name of the function. You pass an anonymous function inside it as the first argument. If we reduced it in complexity, it would look like this:

var $ = function( arg1 ){
  /* Internals */
};

If we now called this, it would look like this:

$("foo");

This code "foo"is our first argument. Suppose now that we replaced our "foo"with another function:

var callback = function(){
  alert("Hello World");
};

If we passed this to our function $, it would look like this:

$( callback );

But we really do not need to use a named function, we could use an anonymous function:

$(function(){
  alert("Hello World");
});

, ? - $ , , . , .

jQuery , jQuery , DOM . , , DOM .

+2
0

All Articles