(function( $ ){
MY_SINGLETON_OBJ = MY_SINGLETON_OBJ || (function () { // initialize the singleton using an immediate anonymous function which returns an object
// init here (only happens once even if this plugin is included multiple times)
console.log("Initialized");
return {
version: "0.1"
// return values that are to be accessible from the singleton
};
})();
$.fn.MyJqueryObjectMethod = function (a, b, c) {
// perform tasks
return this; // maintain chainability
};
})(jQuery);
单身人士正在污染全局命名空间。有没有更好的方法来定义它?
答案 0 :(得分:0)
在我看来它会起作用,但我认为你至少应该全局声明你的单身而不是使用隐含的定义。
你不必那么棘手。您可以轻松地执行此操作,我认为它更具可读性和显而易见性:
// explicit global definition
var MY_SINGLETON_OBJ;
(function( $ ){
if (!MY_SINGLETON_OBJ) {
// initalize the singleton here
MY_SINGLETON_OBJ = {};
MY_SINGLETON_OBJ.prop1 = 1;
}
$.fn.MyJqueryObjectMethod = function (a, b, c) {
// perform tasks
return this; // maintain chainability
};
})(jQuery);