Reputation: 32758
$('li').each(function(index) {
alert(index + ': ' + $(this).text());
});
I'm new to jquery, in the above statement for each 'li' element a new copy of the anonymous function is created in memory or a single copy is used for all.
Upvotes: 0
Views: 227
Reputation: 26699
Only once. JavaScript always use references. And your questions is about javascript and functional programming in general, not about jQuery, which is just a framework / library :)
Upvotes: 2
Reputation: 30498
Think of the function like a variable passed to another function:
So, our function each
might have the definition:
function Each(somefunc)
{
for (var item in $(this)) /*the jQuery collection*/){
someFunc();
}
}
So, it it only one function, called many times
Note: this is not how it is actually implemented!
This is an implementation from one version of jQuery. I've added comments to denote the iteration over the collection:
each: function( object, callback, args ) {
var name, i = 0, length = object.length;
if ( args ) {
if ( length === undefined ) {
for ( name in object ) //<--note the iteration over the collection
if ( callback.apply( object[ name ], args ) === false )
break;
} else
for ( ; i < length; ) //<--note the iteration over the collection
if ( callback.apply( object[ i++ ], args ) === false )
break;
// A special, fast, case for the most common use of each
} else {
if ( length === undefined ) {
for ( name in object ) //<--note the iteration over the collection, etc, etc
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
}
return object;
Upvotes: 2
Reputation: 254886
It is only one anonymous function created, but called several times.
Upvotes: 4
Reputation: 3129
I believe that the same function is used and called on each entry.
Upvotes: 0