2017-12-02 12 views
0

私はjavascriptモジュールパターンを認識していますが、私は2種類のモジュールパターンを使用しており、アーキテクチャの観点からそれらの違いを知りたいと思います。Javascriptモジュールパターン - 違い

// PATTERN ONE 
var module = (function() { 
    var _privateVariable = ''; 

    var _privateMethod = function() { 
    var _this = this; 
    // private method def 
    // can use _this._privateVariable 
    console.log('Inside a private method!'); 
    }; 

    var publicMethod = function() { 
    var _this = this; 
    // public method def 
    // can use _this._privateVariable 
    // can call _privateMethod(); 
    }; 

    return { 
    publicMethod: publicMethod 
    }; 
})(); 

// PATTERN TWO 
var module = (function() { 
    var wrapper = { 
    _privateVariable: '', 

    _privateMethod: function() { 
     var _this = this; 
     // private method def 
     // can use _this._privateVariable 
     console.log('Inside a private method!'); 
    }, 

    publicMethod: function() { 
     var _this = this; 
     // public method def 
     // can use _this._privateVariable 
     // can call _privateMethod(); 
    }, 
    }; 

    return { 
    publicMethod: wrapper.publicMethod 
    }; 
})(); 

これらの両方のパターンは、それらのいずれかを使用して有意差がある私

  1. のために同じことを行うように見えますか?
  2. これらのパターンの1つを避ける必要がありますか?
  3. どちらかの方が良い方法がありますか?
+1

唯一の違いは、バージョン2ではメソッド自体の代わりにメソッドの結果を返すことです。 –

+0

esモジュールを使用することもできますが、 –

+0

のバーベルが必要です。2番目のスニペットは、「エクスポート」する代わりに* public * method()を呼び出します。 – Bergi

答えて

1

実際、言及した2つのパターンには違いはありません。私が見る違いは、第二のパターンが避けることができる余分な変数としてwrapperを使用することだけです。あなたが現在のものではなく、複雑なオブジェクトを返すようにしたいかもしれない他の例を、考慮

、その後、第二のパターンは、非常に便利であるなどのため

var wrapper = { 
_privateVariable: '', 

_privateMethod: function() { 
    var _this = this; 
    console.log('Inside a private method!'); 
}, 

publicMethod: function() { 
    var _this = this; 
}, 

publicMethod2: function() { 
    var _this = null; 
}, 

publicMethod3: function(default) { 
    var _this = default; 
}, 
}; 

return { 
    publicMethod: wrapper 
}; 
関連する問題