想把自己的功能做成可重複使用的 jQuery 插件嗎?jQuery 的擴充主要分成「類級別」與「物件級別」兩種,本文帶你搞懂它們的差異與各自的開發方式。
類級別可以理解為直接擴充 jQuery 這個「類」,最典型的例子就是 $.ajax(...),它是類似靜態方法的用法。開發時使用 $.extend:
$.extend({
add: function(a,b){ return a+b; },
minus: function(a,b){ return a-b; }
});
// 呼叫
var i = $.add(3,2);
var j = $.minus(3,2);
物件級別則是針對選到的元素做擴充,例如 $("#table").changeColor(...),開發時使用 $.fn.extend:
$.fn.extend({
check: function(){ return this.each(function(){ this.checked=true; }); },
uncheck: function(){ return this.each(function(){ this.checked=false; }); }
});
// 呼叫
$('input[type=checkbox]').check();
$('input[type=checkbox]').uncheck();
若想避免污染全域,也可把相關方法收進自訂命名空間:
$.xy = {
add: function(a,b){ return a+b; },
minus: function(a,b){ return a-b; },
voidMethod: function(){ alert("void"); }
};
var i = $.xy.add(3,2);
$.xy.voidMethod();
簡單記:$.extend 對應 $.method(),而 $.fn.extend 對應 $(selector).method(),選對工具是寫好插件的關鍵。