0
(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);

单例正在污染全局命名空间。有没有更好的方法来定义它?

4

1 回答 1

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);
于 2012-07-15T02:55:31.493 回答