jQuery 除了操作 DOM,也可以透過閉包來封裝自訂的類別,把私有變數與公有方法清楚區隔開來。以下是一個簡單的寫法:
(function ($) {
$.DragField = function (arg) {
var name = "你好"; // 私有變數,外部無法直接存取
this.testFun = function () {
// 加上 this 後成為公有方法,外部可以呼叫
alert(arg.title + "," + name);
};
};
})(jQuery);
var a = new $.DragField({ title: "Hi" });
var b = new $.DragField({ title: "Hello" });
a.testFun();
b.testFun();
這種寫法把 $ 作為參數傳入立即執行函式,既能安全地掛載方法到 jQuery 命名空間,又能透過閉包特性保護私有變數,是擴充 jQuery 時很實用的技巧。