0

グローバル オブジェクトを 1 つだけ持つように、javascript でネストされたクラス定義を作成しようとしています。

現時点では、次のような新しいクラスを定義しています。

FOO.Navigation.Sidebar.Tooltip = function()
{
};

したがって、各関数定義では、ネストされたクラスの名前空間全体を繰り返す必要があります。

FOO.Navigation.Sidebar.Tooltip.prototype.show = function()
{
  /* do something here */
};

クラスを作成するために名前空間関数を導入しました。

FOO = { /* ... */ }

FOO.namespace = function(namespaceString)
{
  var namespaceParts = namespaceString.split('.');
  var currentRoot = FOO;
  var index = 0;

  // Skip the first namespacePart, if it is already "FOO"
  if ("FOO" == namespaceParts[0])
  {
  index = 1;
  }

  var currentPart;  
  for(index; index < namespaceParts.length; index++)
  {     
    // This is the next element in the namespace hierarchy.
    currentPart = namespaceParts[index]; 
    // Add a new map for the currentPart to the root (if it does not exist yet). 
    currentRoot[currentPart] = currentRoot[currentPart] || {};
    // The currentPart will be the new root in the next loop.
    currentRoot = currentRoot[currentPart];
  }

  return currentRoot;
};

これを使用して、次のように見える以前の定義のより読みやすいバージョンを作成します。

FOO.Navigation.Sidebar.Tooltip = function()
{
  this.hallo = "world";
};

var tooltip = FOO.Navigation.Sidebar.Tooltip;

tooltip.prototype.show = function()
{
  /* do something */
};

これにより、新しいグローバル変数 "tooltip" が作成され、クラス名を 2 回入力する必要があります。したがって、次のような無名関数を使用することを考えました。

(function(tooltip) {
  tooltip = function()
  {
    this.hello = "world";
  };

  tooltip.prototype.show= function()
  {
    /* do something */
  };
}) (FOO.namespace("FOO.Navigation.Sidebar.Tooltip"))

新しい関数定義を「ツールチップ」に割り当てるため、これは明らかに機能しません。

私の質問は、グローバル変数を作成せずにクラス名を一度だけ書き込む方法があるかどうかです。

4

1 に答える 1

0

Module Patternの実装を作成しようとしているように見えます。モジュールは通常、単一インスタンス オブジェクトの作成に使用されます。ただし、新しいクロージャ (関数) を返すファクトリ メソッドを Module に簡単に追加できます。

tooltip上記で貼り付けたコードを使用すると、クロージャー内の提供された変数にメソッドを直接アタッチできます。例えば:

(function(Tooltip) {
    // 'Static' method added to the module definition.
    Tooltip.hello = function() { 
        alert("Hello!");
    };

    // Factory method which returns a new object.
    Tooltip.create(message) {
        return { 
            this.message = message;
            this.show = function() { /* ... */ }
        };
    }
})(FOO.namespace("FOO.Navigation.Sidebar.Tooltip"));

hello次に、Tooltipでメソッドを呼び出すことができます。

// Invoke a static method.
FOO.Navigation.Sidebar.Tooltip.hello();​

// Create a new ToolTip instance.
var myToolTip = FOO.Navigation.Sidebar.Tooltip.create("Hello World");
myToolTip.show();

階層的なクラス構造を作成したい場合は、Backbone.jsなどの一般的な JavaScript ライブラリの 1 つを検討することをお勧めします。

于 2012-04-05T09:48:14.653 に答える