자바 스크립트에서 중첩 된 클래스 정의를 만들어 전역 개체를 하나만 만들려고합니다. 순간추가 전역 개체를 만들지 않고 중첩 된 클래스 정의
우리는이 같은 새로운 클래스를 정의 :
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"))
.
내 질문에, 전역 변수를 더 이상 만들지 않고 클래스 이름을 한 번만 작성하는 방법이 있다면.
나는 자바가 아니라 자바 스크립트를 쓰고 있음을 상기시켜 준다. 이 모든'foo.bar.baz.trev.cat.mouse' 네임 스페이스 malarkey는 JavaScript에 속하지 않습니다. – Matt
글쎄, 우리는 우리의 C++ 개발자가 프레임 워크에보다 쉽게 접근 할 수 있도록 노력하고 있습니다. 그래서 우리는 추가 글로벌 변수 등을 피하려고합니다. –