開發多個 jQuery 插件後萃取的 10 條架構準則,確保程式碼可維護、高效能、易擴展。
(function($) { /* plugin code */ })(jQuery);
防止全域汙染,內部變數不外洩。$.extend 合併
var defaults = { mode: 'Pencil', lineWidth: 2 };
var settings = $.extend({}, defaults, options || {});
使用者可部分覆蓋,預設值不被修改。this
$.fn.myPlugin = function(options) {
return this.each(function() { /* ... */ });
};
讓 $("#el").myPlugin().css("color","red") 可行。var defaults = { ... }; // 外部:只建立一次
$.fn.myPlugin = function(options) {
return this.each(function() { /* 每個元素執行 */ });
};
避免重複建立相同物件/函數,節省記憶體。function Canvas(settings) { this.settings = settings; return this; }
Canvas.prototype = {
generate: function() { /* ... */ },
draw: function() { /* ... */ }
};
優點:方法共享不重複建立、引用比新建快、程式碼組織清晰。prototypethis 正確指向實例var $this = this 保存實例參考
generate: function() {
var $this = this;
button.click(function() { $this.someFunc($this); });
},
someFunc: function($this) { /* 這裡的 this 是 button,需靠 $this 存取實例 */ }
解決回調函數中 this 指向錯誤問題。function Canvas(settings) { this.settings = settings; }
方法間直接 this.settings.xxx 存取,避免層層傳參。generate() appendColors() colorSelect() colorHoverOn() colorHoverOff() appendToElement() showPalette() hidePalette()方便覆寫、測試、復用。
var lineWidth = $("#container").wPaint("lineWidth");
$("#container").wPaint("lineWidth", "5");
僅需少量代碼即可大幅提升插件彈性。這 10 條準則構成一套可複製貼上的插件骨架,核心邏輯集中在 prototype 方法,新專案只需替換業務代碼即可快速產出穩定插件。