jQuery.extend()與 jQuery.fn.extend()比較

來源:互聯網
上載者:User

標籤:jquery擴充

    • 相同點
    • 不同點
      • jQueryextend
      • jQueryfnextend
    • 程式碼範例

相同點

兩者都是用來擴充 jQuery,為 jQuery添加方法的,在開發jQuery 的相關外掛程式時經常用到。

不同點jQuery.extend()

為 jQuery 類本身添加類方法,即為靜態方法;

調用添加的方法時只能通過 jQuery 本身來調用,jQuery 執行個體對象是無法調用新添加的方法的。比如 添加了 show 和 hide 方法,則調用方式為: jQuery.show()和 jQuery.hide().

jQuery.fn.extend()

看 jQuery 的原始碼時會看到: jQuery.fn=jQuery.prototype,不難發現 jQuery.fn實際即為 jQuery 的原型。則調用jQuery.fn.extend()實際是在擴充jQuery.prototype對象的方法。由於 jQuery原型中的所有成員方法會被所有jQuery執行個體對象繼承,則只要是 jQuery 執行個體對象就有添加的方法。

與 jQuery.extend()不同,jQuery.fn.extend()是為jQuery 原型添加方法,即為jQuery執行個體對象的成員方法。

調用方式也發生了改變,不用通過 jQuery 本身來調用添加的方法,所有 jQuery 執行個體對象都可以調用。

程式碼範例
<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title>jquery.extend()</title></head><body><div id="sample">extend</div></body><script src="jquery-1.11.0.js"></script><script>    $(document).ready(function($){        jQuery.extend({            show:function(){                alert("show message!");            },            hide: function () {                alert("hide message!");            }        });        jQuery.hide();        jQuery.show();//使用jQuery本身調用新添加的方法    })    jQuery(function($){        jQuery.fn.extend({            show:function(){                alert("show message!");            },            hide: function () {                alert("hide message!");            }        });        $("#sample").show();        $("#sample").hide();//使用jQuery 執行個體對象調用新添加的方法    })</script></html>

jQuery.extend()與 jQuery.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.