5

私は奇妙な方法で構築されたJSファイルに出くわしました:

var modal = (function(){
  var method = {};

  // Center the modal in the viewport
  method.center = function () {};

  // Open the modal
  method.open = function (settings) {};

  // Close the modal
  method.close = function () {};

  return method;
}());

関数を「モーダル」オブジェクトにラップする部分は理解していますが、すべての関数をバインドmethodして最後に返すのはなぜですか?

4

2 に答える 2

6

これは、機能をモジュールにグループ化し、グローバル変数を取り除くための設計パターンです。これはより良いコードにつながります。

  1. 関数呼び出しは、「クロージャー」、つまりその関数内で宣言されたすべての変数のスコープを作成します。それらは関数が終了した後も残り、関数の外では見えません。

           var modal = (function(){
           var method = {};
           // Center the modal in the viewport
           method.center = function () {};
    
          // Open the modal
          method.open = function (settings) {};
    
          // Close the modal
          method.close = function () {};
    
          return method;
        }());  // This function call here creates a "closure" ( scope ) 
    
  2. モジュールの特定のメンバーをモジュールの外部で使用できるようにするには、それらを関数から返す必要があります。ここでreturn methodはまさにそれを行いmethod、外部で使用できるモジュールのパブリック オブジェクトを作成します。

  3. openなどの個別の変数を作成する代わりにclose、関連する関数がプロパティ (オブジェクトのキー) としてメインmethodオブジェクトに割り当てられるため、単一のオブジェクトを返すと、関連するすべての関数にアクセスできるようになります。これは、クロージャー スコープ内の識別子 (名前) の数を減らす目的にも役立ちます。

modularこのパターンに関するこの非常に優れた記事を読んでください。

http://www.yuiblog.com/blog/2007/06/12/module-pattern/

于 2013-05-16T18:22:56.287 に答える
3

その特定のコードについては、利点はありません。以下と同じです。

var modal = {

  // Center the modal in the viewport
  center: function () {},

  // Open the modal
  open: function (settings) {},

  // Close the modal
  close: function () {},

};

ただし、関数にローカル変数を入れる場合は別の問題です。

var modal = (function(){

  // a variable that is private to the object
  var local = 'hello world';

  var method = {};

  // Center the modal in the viewport
  method.center = function () {};

  // Open the modal
  method.open = function (settings) {};

  // Close the modal
  method.close = function () {};

  return method;
}());

オブジェクト内のすべてのメソッドがプライベート変数にアクセスできるようになりましたが、オブジェクトの外部から直接アクセスすることはできません。

于 2013-05-16T18:25:12.600 に答える