开发者

Question regarding anonymous function in jQuery

开发者 https://www.devze.com 2023-03-20 12:01 出处:网络
$(\'li\').each(开发者_如何学Gofunction(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
$('li').each(开发者_如何学Gofunction(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.


It is only one anonymous function created, but called several times.


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;


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 :)


I believe that the same function is used and called on each entry.

0

精彩评论

暂无评论...
验证码 换一张
取 消