11

私の Web アプリケーションでは、次のように JavaScript で名前空間を作成しています。

var com = {example: {}};
com.example.func1 = function(args) { ... }
com.example.func2 = function(args) { ... }
com.example.func3 = function(args) { ... }

また、「プライベート」(これは JS に存在しないことはわかっています) 名前空間変数を作成したいのですが、どのデザイン パターンを使用するのが最適かわかりません。

それは次のようになります。

com.example._var1 = null;

それとも、デザインパターンは別のものでしょうか?

4

3 に答える 3

9

Douglas Crockfordは、「プライベート」変数を使用してオブジェクトを作成できる、いわゆるモジュール パターンを普及させました。

myModule = function () {

        //"private" variable:
        var myPrivateVar = "I can be accessed only from within myModule."

        return  {
                myPublicProperty: "I'm accessible as myModule.myPublicProperty"
                }
        };

}(); // the parens here cause the anonymous function to execute and return

しかし、あなたが言ったように、Javascriptには本当にプライベート変数がありません。これは、他のものを壊すややこしいものだと思います。たとえば、そのクラスから継承してみてください。

于 2010-11-10T20:36:25.353 に答える
8

クロージャーは、プライベート変数をシミュレートするために、次のように頻繁に使用されます。

var com = {
    example: (function() {
        var that = {};

        // This variable will be captured in the closure and
        // inaccessible from outside, but will be accessible
        // from all closures defined in this one.
        var privateVar1;

        that.func1 = function(args) { ... };
        that.func2 = function(args) { ... } ;

        return that;
    })()
};
于 2010-11-10T20:32:08.280 に答える