jquery end()函数,pushStack()函数源码解析

实例:操作一个ul列表,添加点击事件

1 $('.list')
2   .find('.list-item').click(function(){...}).end()
3   .click(function(){...});

这段函数用到了end,将对象转换成了find操作之前的$('.list')的jquery父对象。

end函数

1 end: function() {
2     return this.prevObject || this.constructor(null);
3 },

重点 this.prevObject,find中调用了pushStack

find函数

// 一个新的ret,有prevObject, context, selector做了更新
ret = this.pushStack( "", "find", selector );

// 循环在this对象下的每一个dom元素下查找,结果放入ret中
jQuery.find( selector, this[i], ret );

// 结果返回,即为子类对象
return ret

pushStack函数 

注释解释:取一个数组中的元素,将其放入堆上,返回新的堆上的元素集合(jQuery对象)

怎么弹:end弹出

哪些函数有pushStack操作,find,slice, map, not, filter, closest, add, before, after, replaceWith, append等添加操作

// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {

    // Build a new jQuery matched element set
    var ret = jQuery.merge( this.constructor(), elems );

    // Add the old object onto the stack (as a reference)
    ret.prevObject = this;

    ret.context = this.context;

    if ( name === "find" ) {
        ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
    } else if ( name ) {
        ret.selector = this.selector + "." + name + "(" + selector + ")";
    }

    // Return the newly-formed element set
    return ret;
},

this.constructor(null)

A:即是jQuery(null)一个空的jQuery对象

elems是什么

A:即新生成jQuery对象ret填充的对象

jQuery.merge(first, last)

官方解释 Merge the contents of two arrays together into the first array.

 将两个数组内容合并 ,first是被merge的,last数组不会被改变

merge: function( first, second ) {
    var l = second.length,
        i = first.length,
        j = 0;

    if ( typeof l === "number" ) {
        for ( ; j < l; j++ ) {
            first[ i++ ] = second[ j ];
        }

    } else {
        while ( second[j] !== undefined ) {
            first[ i++ ] = second[ j++ ];
        }
    }

    first.length = i;

    return first;
}

 

 

 

posted @ 2013-02-20 14:14  zzu-han  阅读(2067)  评论(2编辑  收藏  举报