- jQuery.fn.extend(object);
- jQuery.extend(object);
- jQuery.extend(object); 爲擴展jQuery類本身.爲類添加新的方法。
- jQuery.fn.extend(object);給jQuery對象添加方法。
fn 是什麼東西呢。查看jQuery代碼,就不難發現。
- jQuery.fn = jQuery.prototype = {
- init: function( selector, context ) {//....
- //......
- };
原來 jQuery.fn = jQuery.prototype.對prototype肯定不會陌生啦。
雖然 javascript 沒有明確的類的概念,但是用類來理解它,會更方便。
jQuery便是一個封裝得非常好的類,比如我們用 語句 $("#btn1") 會生成一個 jQuery類的實例。
jQuery.extend(object); 爲jQuery類添加添加類方法,可以理解爲添加靜態方法。如:
- $.extend({
- add:function(a,b){return a+b;}
- });
便爲 jQuery 添加一個爲 add 的 “靜態方法”,之後便可以在引入 jQuery 的地方,使用這個方法了,
- $.add(3,4); //return 7
jQuery.fn.extend(object); 對jQuery.prototype進得擴展,就是爲jQuery類添加“成員函數”。
比如我們要開發一個插件,做一個特殊的編輯框,當它被點擊時,便alert 當前編輯框裏的內容。可以這麼做:
- $.fn.extend({
- alertWhileClick:function(){
- $(this).click(function(){
- alert($(this).val());
- });
- }
- });
- $("#input1").alertWhileClick(); //頁面上爲:<input id="input1" type="text"/>