0

このRevealing Module Patternの代わりに使用することをお勧めします...

var MyModule = ( function() {
  function Method1() { alert( 'method1' ); }
  function Method2() { Method1(); alert( 'method2' ); }
  function Method3() { Method1(); alert( 'method3' ); }
  function Method4() { Method1(); alert( 'method4' ); }
  return { Method1 : Method1,    // these
           Method2 : Method2,    // lines
           Method3 : Method3,    // are 
           Method4 : Method4 };  // redundant...
} )();

MyModule.Method1(); 
MyModule.Method2();

... このわずかな違い:

var MyModule = {};
( function() {
  var Method1 = MyModule.Method1 = function () { alert( 'method1' ); };
  var Method2 = MyModule.Method2 = function () { Method1(); alert( 'method2' ); };
  var Method3 = MyModule.Method3 = function () { Method1(); alert( 'method3' ); };
  var Method4 = MyModule.Method4 = function () { Method1(); alert( 'method4' ); };
} )();

MyModule.Method1();
MyModule.Method2();

結局100%同じなの?これは良い習慣と見なされますか?

4

3 に答える 3

1

結局100%同じなの?

最終結果は同じです。

これは良い習慣と見なされますか?

それは主に意見の問題です。あなたの例は、RMP のいくつかのバリエーションのうちの 2 つであり、どちらも有効です。

一般的に見られる 3 番目のバリエーションは、2 番目のバリエーションに似ていますが、特定の目的があります。

var MyModule = function(mod) {
  var Method1 = mod.Method1 = function () { alert( 'method1' ); };
  var Method2 = mod.Method2 = function () { Method1(); alert( 'method2' ); };
  var Method3 = mod.Method3 = function () { Method1(); alert( 'method3' ); };
  var Method4 = mod.Method4 = function () { Method1(); alert( 'method4' ); };
  return mod;
}(typeof MyModule === "undefined" ? {} : MyModule);

その目的は、すでに定義されているモジュールに追加できるようにすることですが、まだ定義されていない場合は作成できます。

于 2014-12-10T09:15:53.837 に答える
1

それは同じではありません。モジュールの名前をいつでも変更したり、別の名前で使用したりする場合は、変更できません。

また、配列の最後にあるオブジェクトを返すことで、オブジェクトから何が公開されているかを完全に明確にします。

于 2014-12-10T09:16:14.977 に答える