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 );
}
- 当执行
li.slice(2)
时,进入slice
方法,this
指的是li,temp
为后3个li
,返回this.pushStack
,进入pushStack
方法,参数为temp
,首先将temp
封装成jQuery
对象并赋值给ret
,即待返回的对象,将this
赋值给ret
的prevObject
属性(方便后续调用end
方法),返回ret
。此时ret
的结构包括
{
jQuery:temp
prevObject:li
context:document
}
- 当执行
s.end()
时:
end: function() {
return this.prevObject || this.constructor(null);
},
返回s
的prevObject
,即li