简体   繁体   English

关于 jQuery 中匿名 function 的问题

[英]Question regarding anonymous function in jQuery

$('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.我是 jquery 的新手,在上述语句中,对于每个“li”元素,在 memory 中创建了一个匿名 function 的新副本,或者单个副本用于所有。

It is only one anonymous function created, but called several times.它只是一个匿名的 function 创建的,但被调用了几次。

Think of the function like a variable passed to another function:将 function 想象成传递给另一个 function 的变量:

So, our function each might have the definition:所以,我们的 function each可能都有定义:

function Each(somefunc)
{
    for (var item in $(this)) /*the jQuery collection*/){
        someFunc();
    }
}

So, it it only one function, called many times所以,它只有一个 function,调用了很多次

Note: this is not how it is actually implemented!注意:这不是它的实际实现方式!

This is an implementation from one version of jQuery.这是 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. JavaScript 始终使用引用。 And your questions is about javascript and functional programming in general, not about jQuery, which is just a framework / library:)你的问题是关于 javascript 和一般的函数式编程,而不是关于 jQuery,这只是一个框架/库:)

I believe that the same function is used and called on each entry.我相信每个条目都使用和调用相同的 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM