jQuery源码分析-----pushStack

来源:互联网 发布:远程数据采集器 编辑:程序博客网 时间:2024/06/05 04:29

pushStack是jQuery底层方法

pushStack方法虽然在高层不会用到,但很多方法都会调用它

举例:
html结构为ul下5个li

var li = $('li');var s = li.slice(2);var end = s.end();pushStack:// Take an array of elements and push it onto the stack// (returning the new matched element set)pushStack: function( elems ) {    // 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;    // Return the newly-formed element set    return ret;}slice: function() {    var temp = slice.apply( this, arguments );    return this.pushStack( temp );}
  1. 当执行li.slice(2)时,进入slice方法,this指的是li,temp为后3个li,返回this.pushStack,进入pushStack方法,参数为temp,首先将temp封装成jQuery对象并赋值给ret,即待返回的对象,将this赋值给retprevObject属性(方便后续调用end方法),返回ret。此时ret的结构包括
{    jQuery:temp    prevObject:li    context:document}
  1. 当执行s.end()时:
end: function() {    return this.prevObject || this.constructor(null);},

返回sprevObject,即li

原创粉丝点击