关于jQuery中匿名函数的问题

时间:2011-07-14 11:51:25

标签: javascript jquery functional-programming anonymous-function

$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
});

我是jquery的新手,在每个'li'元素的上述语句中,匿名函数的新副本在内存中创建,或者单个副本用于所有。

4 个答案:

答案 0 :(得分:4)

只创建了一个匿名函数,但多次调用。

答案 1 :(得分:2)

将函数看作传递给另一个函数的变量:

因此,我们的函数each可能有以下定义:

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

所以,它只有一个函数,多次调用

注意:这不是它实际实现的方式!

这是一个jQuery版本的实现。我添加了注释来表示对集合的迭代:

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;

答案 2 :(得分:2)

只有一次。 JavaScript总是使用引用。你的问题一般是关于javascript和函数式编程,而不是关于jQuery,它只是一个框架/库:)

答案 3 :(得分:0)

我相信每个条目都使用和调用相同的函数。