guest
guest

Reputation: 2224

How does anonymous functions work in jQuery/Javascript?

How does anonymous function know what parameters are being passed in? For example,

Case 1:

$( "li" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
});

Case 2:

$( "li" ).each(function(e) {
  e.preventDefault();
});

Case 3:

$( "li" ).each(function( index, element ) {
  console.log( index + ": " + element + $( this ).text() );
});

In each of these cases, how does the anonymous function know what e, index, element are?

Upvotes: 0

Views: 151

Answers (3)

Jan
Jan

Reputation: 8131

naive implementation of each function:

function $(selector) {

    var elements = document.querySelectorAll(selector);

    return {
        each: function (fn) {
            for (var i = 0; i < elements.length; i++) {
                fn(i, elements[i]);
            }        
        }
    };
}

The jQuery function returns an object with an each function. This function has access to the matched elements and iterates over them. It can call the function you gave it on every iteration and pass the current index and corresponding element to it.

Your second case doesn't make much sense to me. As far as I know jQuery, no event is passed to the each function.

Upvotes: 0

minopret
minopret

Reputation: 4806

If we can speak of each as if it's a little robot, each tells the function what its arguments are. It picks up the collection and the function, puts the elements of the collection into the function one at a time, and sticks the outputs together as a collection. http://api.jquery.com/jquery.each/

You should understand that when you write an anonymous function, it's both a procedure and an object. You are simultaneously defining for Javascript how to carry out that function ("knowing how" to call it) and what that function is ("knowing that" it is a particular object). Some languages are still in use where a function is not an object. So maybe that fact was confusing when you encountered it here.

Upvotes: 0

Quentin
Quentin

Reputation: 943142

Because the code in each will call the function you pass it with the arguments.

function notEach(callback) {
    callback(1,2,3);
}

notEach(function (one, two, three) {
    console.log(one, two three);
});

Upvotes: 2

Related Questions