想知道 jQuery 1.7.1 的 jQuery.fn 上到底定義了哪些屬性與方法,直接打開原始碼看最準:


熟悉 JavaScript 物件導向的人都認識它——用來回傳建立該物件的建構函式:
function Person(){}; var person=new Person(); alert(person.constructor); //function Person(){}
但我們寫繼承時,習慣把所有的原型屬性與方法一次塞進一個物件字面值,這會導致 constructor 的指向「跑掉」:
function Person(){ } Person.prototype={ say:function(msg){ alert(msg); } } var person=new Person(); person.say('hello'); alert(person.constructor); //function Object(){[native code]}
因為字面值物件本身是 Object 的實例,constructor 自然就指向 Object 了。為了修正這個「錯誤」,通常需要手動把它改回來——這正是原始碼裡 constructor: jQuery 這行的用意。
對一般使用者幾乎沒用,主要是給開發 jQuery 外掛或改造 jQuery 的人使用。它會回傳取得目前這個 jQuery 物件時所用的選擇器字串:
var obj=$('div a'); console.log(obj.selector);//'div a'
回傳目前使用的 jQuery 版本:
console.log($('body').jquery); //1.7.1
回傳該 jQuery 物件包含的元素個數:
console.log ( $('body') .length); //1
以上四個屬性的原始碼長這樣:
constructor: jQuery, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.7.1", // The default length of a jQuery object is 0 length: 0,
// The number of elements contained in the matched element set size: function() { return this.length; },
它就是回傳 length 屬性。兩者等效,但建議直接用 length,可以省下一次函式呼叫的開銷。
toArray: function() { return slice.call( this, 0 ); },
把 jQuery 集合中的所有 DOM 元素還原成一個純陣列:
alert($('li').toArray()); [<li id="foo">, <li id="bar">]
這裡的 slice 是 jQuery 建構函式一開始就保留下來的 Array 原型方法:
// Save a reference to some core methods 87 toString = Object.prototype.toString, 88 hasOwn = Object.prototype.hasOwnProperty, 89 push = Array.prototype.push, 90 slice = Array.prototype.slice, 91 trim = String.prototype.trim, 92 indexOf = Array.prototype.indexOf,
透過 call 進行「物件冒充」,傳入 0 表示不截取,於是就得到一個乾淨的陣列,完成 jQuery 物件到純陣列的轉換。這招在任何「類陣列物件」上都通用:
<!doctype html> <html> <head> <meta charset='utf-8'/> <title>jQuery源碼分析-原型屬性和方法</title> </head> <body> <div> </div> <div></div> </body> <script src='jquery-1.7.1.js'></script> <script> var divs=document.getElementsByTagName('div'); console.log(divs); //[div, div] alert(divs instanceof Array); //fasle alert(Array.prototype.slice.call(divs,0) instanceof Array); //true </script> </html>
getElementsByTagName() 回傳的是 HTMLCollection,不是陣列, therefore 沒有陣列的那些方法;套上 Array.prototype.slice.call(x, 0) 之後就變成真陣列了。
// Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); },
get() 的作用與 eq() 有個關鍵差異:get() 回傳的是原生的 DOM 節點物件,eq() 回傳的仍是 jQuery 物件。
它接受一個參數:不帶參數時呼叫 toArray() 回傳包含所有元素的陣列;傳正數時直接用索引取值;傳負數時用「長度 + 索引」換算,因此 .get(-1) 就是最後一個元素。這個「正負索引都支援」的寫法本身就很值得學。若傳入的不是數字,或超出範圍,會回傳 undefined。
讀 jQuery 原始碼除了更懂它怎麼運作,也能累積不少實用的 JavaScript 技巧——像這種「用 call 借用原型方法」與「負索引換算」的模式,在自己的專案裡都寫得上去。