128 ret.context = this.context;
130 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;
137 },
121 行開始的 pushStack 方法用來將通過數組傳遞的一個集合,格式化成為一個標準的 jQuery 對象,這樣就可以使用 jQuery 提供的方法進行操作了。第 123 將數組轉化為一個 jQuery 對象。參見 91 行。
126 行通過 prevObject 屬性指向原來的數組對象,128行保存當前的環境引用。
130 行檢查是否要在數組上進行進一步的查詢,如果提供了查詢, 那么更新當前的選擇器 selector。
136 行,返回構造完成的 jQuery 對象。
// Force the current matched set of elements to become
// the specified array of elements (destroying the stack in the process)
// You should use pushStack() in order to do this, but maintain the stack
142 setArray: function( elems ) {
// Resetting the length to 0, then using the native Array push
// is a super-fast way to populate an object with array-like properties
this.length = 0;
Array.prototype.push.apply( this, elems );
return this;
},
142 行的 setArray 方法用來將通過參數傳遞進來的數組,替換掉當前的 jQuery 對象中的查詢結果。
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
154 each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
each 方法用來遍歷查詢結果,方法接受一個回調函數,jQuery 將遍歷查詢結果,對于每一個查詢結果對象,調用這個回調函數,并通過參數傳遞 this 和參數引用。
具體的 each 方法見 671 行函數的定義。
671 each: function( object, callback, args ) {
672 var name, i = 0, length = object.length;
673
674 if ( args ) {
if ( length === undefined ) {
for ( name in object )
if ( callback.apply( object[ name ], args ) === false )
break;
679 } else
680 for ( ; i < length; )
if ( callback.apply( object[ i++ ], args ) === false )
break;
// A special, fast, case for the most common use of each
685 } else {
686 if ( length === undefined ) {
687 for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
690 } else
691 for ( var value = object[0];
692 i < length && callback.call( value, i, value ) !== false;
value = object[++i] ){}
693 }
695 return object;
696 },
Each 的第一個參數為一個 jQuery 對象,第二個參數為處理每一個對象的回調函數,第三個參數可以為回調函數提供一個額外的參數。
注意,如果回調函返回假,那么結束遍歷過程。
674 行判斷是否提供了額外的參數,如果沒有提供,那么,執行 685行 else 語句部分的常用遍歷處理。
686 行檢查對象是否提供了 length 屬性,如果沒有,那么 687 行通過 for in 語句直接遍歷對象的所有成員,對于每一個屬性,使用 callback 進行處理,為了將當前的對象作為 this 傳遞給回調函數,使用了 call 的調用方式。
691 行和 692 行處理有 length 屬性的情況,直接通過長度進行遍歷。
如果有參數數組傳遞進來,那么,轉到 675 行進行處理。
檢查對象是否有 length 屬性,如果沒有使用 for in 語句,如果有,使用下標進行遍歷。
680 行處理有 length 屬性的情況,這時,直接通過數組的長度進行遍歷,由于參數使用了數組方式,所以通過 apply 將當前對象作為 this,其他參數作為數組進行調用。
來源:博客園