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 に答える