Java程式員的JavaScript學習筆記(11——jQuery-在“對象”層面擴充)

來源:互聯網
上載者:User

Java程式員的JavaScript學習筆記(11——jQuery-在“對象”層面擴充)
計劃按如下順序完成這篇筆記:
1. 理念。
2. 屬性複製和繼承。
3. this/call/apply。
4. 閉包/getter/setter。
5. prototype。
6. 物件導向類比。
7. jQuery基本機制。
8. jQuery選取器。
9. jQuery工具方法。
10. jQuery-在“類”層面擴充。
11. jQuery-在“對象”層面擴充。
12. jQuery-延伸選取器。
13. jQuery UI。
14. 擴充jQuery UI。
這是筆記的第11篇,我們將對$()返回的對象功能進行擴充,以豐富其屬性和功能,滿足我們的需要。
在第9篇(http://blog.csdn.net/stationxp/article/details/40480185)我們瞭解到jQuery.extend和jQuery.fn.extend其實定義相同。
調用者不同,才導致了兩個函數功能的差別(詳細機制請參見本筆記第3篇)。
 
1、jQuery.fn.extend擴充了誰?jQuery.fn.extend({});
上面語句調用者是jQuery.fn,jQuery.fn是誰?
看下面的jQuery源碼:

var// Define a local copy of jQuery// jQuery 即 jQuery()這個函數,即 $()這個函數jQuery = function( selector, context ) {// The jQuery object is actually just the init constructor 'enhanced'// init的傳回值,即jQuery的傳回值// 第7篇中我們分析了這行代碼,等同於:// var ret = {};// jQuery.fn.init.apply(ret,selector, context, rootjQuery);//以ret為上下文調用init方法// ret.prototype = jQuery.fn.init.prototype; //jQuery.fn.init.prototype隨後會被賦值為 jQuery.fn,這句好關鍵// return ret;return new jQuery.fn.init( selector, context, rootjQuery );},// jQuery.fn 是對jQuery原型的引用,原型中定義了init函數jQuery.fn = jQuery.prototype = {init: function( selector, context, rootjQuery ) {//...// init 函數返回的是 this[0]、this[1]方式返回的數組,是執資料列選取器的結果return jQuery.makeArray( selector, this );}};// Give the init function the jQuery prototype for later instantiation// 將jQuery.fn設定為jQuery選擇jQuery.fn.init.prototype = jQuery.fn;

以上代碼,簡而言之,jQuery.fn是$()函數傳回值的原型對象。

在筆記的第2篇我們學習過,給對象的原型增加屬性或方法,對象也會自動獲得這些方法。

 

2、試試看2.1、擴充方法
Bill<script>jQuery.fn.extend({greeting:function(){console.log('Hi, buddy! I am hailong's friend ' + this.text());}});$('#x').greeting();// Hi, buddy! I am hailong's friend Bill$.greeting();//error : no such method</script>

2.2、可以擴充屬性嗎?
BillSteven<script>jQuery.fn.extend({lord : 'liuhailong ',name : 'jQuery Object'});console.log($('#b').lord); // output : liuhailongconsole.log($('#b').name); // output : jQuery Objectvar b = $('#b'), s = $('#s');b.name = 'Bill';s.name = 'Steven';console.log(b.name,s.name); // output : Bill Steven </script>

正如我們期待的:完美支援。

3、可以做什嗎?有什麼用?可以實現任何你想實現的功能,發揮你的想象力吧!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.