グローバル オブジェクトを 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"))
新しい関数定義を「ツールチップ」に割り当てるため、これは明らかに機能しません。
私の質問は、グローバル変数を作成せずにクラス名を一度だけ書き込む方法があるかどうかです。