Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript oop basics [duplicate]

Possible Duplicate:
$(document).ready shorthand

Can someone help me to 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');
    });
});
like image 366
Nil Pun Avatar asked Jun 18 '26 20:06

Nil Pun


1 Answers

$ is the name of a function. You're passing an anonymous function inside of it as its first argument. If we were to reduce it in complexity, it would look like this:

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

If we were to call this now, it would look like the following:

$("foo");

In this code, "foo" is our first argument. Now suppose we replaced our "foo" with another function:

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

If we passed that into our $ function it would look like this:

$( callback );

But we really don't need to use a named function, we could use an anonymous function:

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

Starting to see the similarities? At some point in the life of $, it will decide it's going to execute the function we're passing in. Until it executes it, our function does nothing.

Now we're talking about jQuery here, and jQuery will execute that function whenever the DOM is ready. So we're passing code in that ought to be executed whenever the DOM is ready.

like image 124
Sampson Avatar answered Jun 21 '26 09:06

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!