var $aaron = $("aaron");
console.log($aaron)
// jQuery 对象栈
// jQuery内部维护着一个jQuery对象栈。每个遍历方法都会找到一组新元素(一个jQuery对象),然后jQuery会把这组元素推入到栈中
// 而每个jQuery对象都有三个属性:context、selector和prevObject,其中的prevObject属性就指向这个对象栈中的前一个对象,而通过这个属性可以回溯到最初的DOM元素集。
// demo
// <ul id="aaron">
// parent
// <li>child</li>
// </ul>
//
// 这个很简单找到ul下面的li,绑定即可
var aaron = $("#aaron");
aaron.find('li').click(function(){
alert(1) //1
})
// 但现在又想给aaron绑定方法,是不是又要重新给aaron绑定?
// 可以回溯到之前的dom元素集合
aaron.find('li').click(function(){
alert(1)
}).end().click(function(){
alert(2)
})
// 源码实现
end: function() {
return this.prevObject || this.constructor(null);
},
// prevObject在什么情况下会产生?
// 答:在构建jQuery对象的时候,通过pushStack方法构建
jQuery.fn.extend({
find: function( selector ) {
...........................省略................................
//通过sizzle选择器,返回结果集
jQuery.find( selector, self[ i ], ret );
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
}
// pushStack:将一个DOM元素集合加入到jQuery栈。
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;
},
转载:https://www.cnblogs.com/aaronjs/p/3387278.html