理解jquery的$.extend()、$.fn和$.fn.extend()

來源:互聯網
上載者:User

標籤:

jQuery為開發外掛程式提供了兩個方法,分別是:

jQuery.fn.extend();

jQuery.extend();

 

jQuery.fn

jQuerr.fn=jQuery.prototype={  init: function(selector,context){   //....  }}

jQuery.fn = jQuery.prototype是對jQuery對象(原型的)的方法進行擴充

jQuery.extend(object)是為jQuery類添加類方法,可以理解為添加靜態方法。如:

jQuery.extend({min: function(a, b) { return a < b ? a : b; },max: function(a, b) { return a > b ? a : b; }});jQuery.min(2,3); //  2 jQuery.max(4,5); //  5

Object jQuery.extend(target,object1,[objectN])

用一個或多個其他對象來擴充一個對象,返回被擴充的對象

var settings = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; jQuery.extend(settings, options); 結果:settings == { validate: true, limit: 5, name: "bar" }

jQuery.fn.extend(object)

對jQuery.prototype進行的擴充,就是為jQuery類添加“成員函數”。jQuery類的執行個體可以使用這個“成員函數”。

比如我們要開發一個外掛程式,做一個特殊的編輯框,當它被點擊時便要alert當前編輯框裡的內容。可以這麼做:

$.fn.extend({              alertWhileClick:function() {                      $(this).click(function(){                                  alert($(this).val());                      });                }       });       $("#input1").alertWhileClick(); // 頁面上為:    

 

$("#input")為一個jQuery執行個體,當它調用成員方法alertWhileClick後,便實現了擴充,每次被點擊時它會先彈出目前編輯器裡的內容。

 

jQuery.extend()的調用並不會把方法擴充到對象的執行個體上,引用它的方法也需要通過jQuery類來實現,如jQuery.init(),而jQuery.extend()的調用把方法擴充到了對象的prototype上,所以執行個體化一個jQuery對象的時候,它就具有了這些方法。

 

jQuery.fn.extend() = jQuery.prototype.extend()

你可以拓展一個對象到jQuery的prototype裡去,這樣的話就是外掛程式機制了。

(function( $ ){$.fn.tooltip = function( options ) {};//等價於var tooltip = {function(options){}};$.fn.extend(tooltip) = $.prototype.extend(tooltip) = $.fn.tooltip})( jQuery );

 

理解jquery的$.extend()、$.fn和$.fn.extend()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.