用 jQuery 寫久了自己動手做插件,幾乎是每個前端開發者的必經之路。jQuery 把插件的擴展方式歸納成兩條清晰的技術路線:一條是類級別(靜態方法),直接掛在 jQuery 這個「類」身上;另一條是對象級別(實例方法),掛在 jQuery.fn 也就是原型上,讓每一個選中的元素集合都能調用。下面把這兩條路線的常見寫法、設計要點與封裝技巧逐一拆解。
類級別插件最典型的代表就是 $.ajax()——它不針對任何 DOM 元素,只是一個掛在 jQuery 命名空間下的工具函數。共有四種常見擴展形式。
jQuery.foo = function() {
alert('This is a test. This is only a test.');
};
jQuery.foo = function() {
alert('This is a test. This is only a test.');
};
jQuery.bar = function(param) {
alert('This function takes a parameter, which is "' + param + '".');
};
調用時與普通函數無異:jQuery.foo();、jQuery.bar('baz');,也可以簡寫成 $.foo();、$.bar('baz');。
寫法更乾淨,也更利於日後維護:
jQuery.extend({
foo: function() {
alert('This is a test. This is only a test.');
},
bar: function(param) {
alert('This function takes a parameter, which is "' + param + '".');
}
});
即便 jQuery 本身已經佔用了大量名稱,插件之間撞名依然防不勝防。實踐中的通用做法是把相關方法收攏進一個獨立命名空間:
jQuery.myPlugin = {
foo: function() {
alert('This is a test. This is only a test.');
},
bar: function(param) {
alert('This function takes a parameter, which is "' + param + '".');
}
};
調用形式變為 $.myPlugin.foo(); 與 $.myPlugin.bar('baz');。這一招看起來樸素,卻能有效杜絕全局污染。
對象級插件才是日常最常用的形態。基本骨架有兩種等價寫法:
(function($) {
$.fn.extend({
pluginName: function(opt, callback) {
// 插件實現邏輯
}
});
})(jQuery);
(function($) {
$.fn.pluginName = function() {
// 插件實現邏輯
};
})(jQuery);
把 jQuery 以實參形式傳入立即執行函數,好處是函數體內部可以放心使用 $ 這個別名,不必擔心與 Prototype 等庫的 $ 衝突。這是行業內公認的標準寫法,請養成習慣。
一個插件最好只暴露一個入口。若你的插件包含成對的功能(例如 doSomething() 與 undoSomething()),可以通過把輔助函數掛成該函數的屬性來避免污染命名空間——畢竟在 JavaScript 裡函數也是對象。
$.fn.hilight = function() {
// 插件實現邏輯
};
// 調用: $('#myDiv').hilight();
$.fn.hilight = function(options) {
var defaults = {
foreground: 'red',
background: 'yellow'
};
var opts = $.extend(defaults, options);
// 插件實現邏輯
};
// 調用
$('#myDiv').hilight({ foreground: 'blue' });
更進一步的做法,是把默認值掛成插件函數的屬性,讓使用者能一行代碼改全局默認:
$.fn.hilight = function(options) {
// 第一個參數傳空對象,避免污染 defaults
var opts = $.extend({}, $.fn.hilight.defaults, options);
// 插件實現邏輯
};
$.fn.hilight.defaults = {
foreground: 'red',
background: 'yellow'
};
使用者於是既可以一次性改默認值:
$.fn.hilight.defaults.foreground = 'blue';
$('.hilightDiv').hilight();
也可以在調用時臨時覆蓋:
$('#green').hilight({ foreground: 'green' });
把關鍵的處理函數(例如格式化文本的 format)也掛到插件對象上,等於把擴展點交給了社群——別人就能「為你的插件寫插件」。
$.fn.hilight = function(options) {
return this.each(function() {
var $this = $(this);
var markup = $this.html();
markup = $.fn.hilight.format(markup);
$this.html(markup);
});
};
$.fn.hilight.format = function(txt) {
return '<strong>' + txt + '</strong>';
};
真實案例是傳說中的 Cycle 插件:它把 transitions 對象公開出來,使用者便能自行定義滾動、滑動、淡出等各種轉場效果。
暴露是強大的,但一旦暴露就背上了向後兼容的包袱。拿不準要不要公開的函數,乾脆別公開。閉包正是那把保護傘:
(function($) {
$.fn.hilight = function(options) {
debug(this);
// ...
};
// 私有調試函數,外部無法訪問
function debug($obj) {
if (window.console && window.console.log) {
window.console.log('hilight selection count: ' + $obj.size());
}
}
})(jQuery);
支持 Metadata 插件後,配置就能直接寫在 HTML 標記裡,做示例頁面時格外省事:
$.fn.hilight = function(options) {
var opts = $.extend({}, $.fn.hilight.defaults, options);
return this.each(function() {
var $this = $(this);
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
// ...
});
};
標記端寫成:
<div class="hilight { background: 'red', foreground: 'white' }">Have a nice day!</div>
<div class="hilight { foreground: 'orange' }">Have a nice day!</div>
<div class="hilight { background: 'green' }">Have a nice day!</div>
一行腳本搞定全部:$('.hilight').hilight();
(function($) {
$.fn.hilight = function(options) {
debug(this);
var opts = $.extend({}, $.fn.hilight.defaults, options);
return this.each(function() {
var $this = $(this);
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
$this.css({
backgroundColor: o.background,
color: o.foreground
});
var markup = $this.html();
markup = $.fn.hilight.format(markup);
$this.html(markup);
});
};
function debug($obj) {
if (window.console && window.console.log) {
window.console.log('hilight selection count: ' + $obj.size());
}
}
$.fn.hilight.format = function(txt) {
return '<strong>' + txt + '</strong>';
};
$.fn.hilight.defaults = {
foreground: 'red',
background: 'yellow'
};
})(jQuery);
閉包 + 默認值 + 可覆蓋的擴展點 + 私有工具函數,這套組合拳足以支撐起規範、耐用且易於協作的前端插件。
一句話記住區別:jQuery.extend(object) 擴展的是類本身,添加靜態方法;jQuery.fn.extend(object) 擴展的是原型,添加實例方法。
而 fn 到底是什麼?翻開源碼便一目了然:
jQuery.fn = jQuery.prototype = {
init: function(selector, context) { /* ... */ }
};
雖然 JavaScript 沒有嚴格意義上的類,但用類的心智模型去理解會輕鬆很多。當我們寫下 $("#btn1") 時,得到的就是一個 jQuery 實例;jQuery.fn.extend() 往原型上加的成員函數,這個實例自然就能調用。
舉個實際例子——做一個被點擊就彈出自身內容的輸入框:
$.fn.extend({
alertWhileClick: function() {
$(this).click(function() {
alert($(this).val());
});
}
});
$("#input1").alertWhileClick();
而靜態方法則這樣添加:
$.extend({
add: function(a, b) { return a + b; }
});
$.add(3, 4); // 返回 7