グローバルオブジェクトを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 */
};
クラス名は二度。 は、だから我々はこのように無名関数を使用してのthougth:私たちは、「ツールチップ」に新しい関数定義をASSINGので、これは明らかに、動作しません
(function(tooltip) {
tooltip = function()
{
this.hello = "world";
};
tooltip.prototype.show= function()
{
/* do something */
};
}) (FOO.namespace("FOO.Navigation.Sidebar.Tooltip"))
。
グローバル変数をそれ以上作成せずにクラス名を1回だけ書く方法があれば、私の質問です。
私はあなたがJavaではなくJavaScriptを書いていることを思い出しています。この 'foo.bar.baz.trev.cat.mouse'名前空間malarkeyはすべてJavaScriptに属していません。 – Matt
さて、私たちはC++開発者にとってよりフレキシブルなフレームワークにしようとしています。そういうわけで、グローバル変数の追加などを避けようとしています。 –