用jquery有一年了,jq很靈巧,API不像其他庫一樣那麼囉嗦,一個css()就可以滿足多種需求,免去了記憶API之苦。jquery的優點就不炫耀了,也遇到一些問題,比如在gbk頁面用getScript載入gbk編碼的js檔案就出現亂碼問題,看了看源碼也未找到蛛絲馬跡,此問題暫且掛起。jquery代碼非常嚴謹、獨具匠心,值得學習,看源碼可以加深javascript的瞭解、學到一些時髦的設計思想。
把jQuery的骨架抽出來看很簡單,唯一出彩的地方就是jQuery返回一個jQuery.fn.init執行個體,這就讓一切變得簡單靈活。
(function( window, undefined ) {<br />// Define a local copy of jQuery<br />var jQuery = function( selector, context ) {<br />// The jQuery object is actually just the init constructor 'enhanced'<br />// jQuery對象是jQuery.fn.init函數的一個執行個體<br />return new jQuery.fn.init( selector, context );<br />}</p><p>jQuery.fn = jQuery.prototype = {<br />init: function( selector, context ) {</p><p>},<br />get : function(){</p><p>}<br />}<br />// 這句保證了 init 方法裡的 this 擁有 jQuery 執行個體的方法 yubo<br />// $("")返回init方法的執行個體<br />jQuery.fn.init.prototype = jQuery.fn;</p><p>// 靜態屬性和方法,通過 jQuery 訪問<br />jQuery.extend({<br />noConflict : function(){}<br />});</p><p>// 執行個體方法,通過 jQuery("") 訪問<br />jQuery.fn.extend({<br /> data: function( key, value ) {}<br />});</p><p>// 把jQuery暴露給全域<br />window.jQuery = jQuery;<br />})(window);