2012-03-10 3 views
1

새 프로젝트를 시작하고 자바 스크립트 ""네임 스페이스 ""를 사용하여 클라이언트 측 코드를 구성하기로 결정했습니다. 문제는 우리가) (자바 스크립트에서 긴 네임 스페이스를 피하는 방법

myProject.components.myComponent.doSomethig처럼 기억하기 dificult입니다 슈퍼 긴 네임 스페이스를 아주 쉽게 끝낼 수 있습니다 것으로 나타났습니다이다;

이렇게하거나 "별칭"을 어떻게 든 만들 수있는 더 좋은 방법이 있습니까?

감사합니다.

당신은 항상 지역 변수에 subnamespace를 저장할 수

답변

3

: 여러 구성 요소를 사용하여 응용 프로그램 코드를 작성하는 경우 마찬가지로

(function() { 
    var comp = {}; 

    // Export our component 
    myProject.components.myComponent = comp; 

    // add things to `comp`; since `comp` and `myProject.components.myComponent` 
    // refer to the same object, adding to `comp` is adding to the one object 
    // they both refer to and so you can access those things via either reference 
})(); 

:

예, 코드는 myComponent 구성 요소를 정의 물건

var myComp = myProject.components.myComponent; 
myComp.func1(); 

이것은 단지 참조 용입니다. 당신은 다른 긴 이름이 작업을 수행하고 또한 당신이 당신의 코드를

// 파일 정리 RequireJS과 코드를 구성 할 수 있습니다 덜이

var getEl = document.getElementById, 
    myEl = getEl('divId'); 

처럼 쓸 수 있습니다 : MyProject를/구성 요소/myComponent.js을

define(function(){ 
     var myComponent ={}; 
     myComponent.func1 = function(){ 
      ... 
     } 
     return myComponent; 
}); 

// 파일 : MyProject를/main.js

require(['myProject/components/myComponent', 'myProject/components/myComponent2'], 
function(comp1, comp2){ 
     var main = {}; 
     main.init = function() { 
      ... 
      comp1.func1(); 
     } 
}); 

// 파일 : myPro ject/index.html

0

:

var myComponent = myProject.components.myComponent; 
1

당신이 당신의 모듈 코드 주위에 기능을 범위 지정 사용하는 경우 (당신은, 당신이해야하지 않는 경우), 당신은 지역의 별칭을 확실히 만들 수 있습니다 주어진 모듈 내의 모든 기능에 의해 공유되는 변수로서 쉽게. 당신이 긴 네임 스페이스에 대한 바로 가기 참조를 만들 수 있습니다 자바 스크립트에서

(function() { 
    var thisComp = myProject.components.thisComponent, 
     thatComp = myProject.components.thatComponent; 

    // Use `thisComp` and `thatComp` 
})(); 
+0

이것은 아마도 가장 보편적 인 해결책 일 것입니다. (단지 "해야"하는 것이 의미가있는 이유에 대해). 범위 지정 함수는 네임 스페이스 충돌을 방지하여 창 개체를 다시 정의해야 나중에 코드에서 재난을 초래할 수 있습니다. – Shane

관련 문제