2011-08-12 3 views
1

저는 JS에서 모든 것을 글로벌로 사용하는 일반적인 웹 개발자입니다. 나는 이제 빛을 보았고 네임 스페이스로 변환하고 싶다. 따라서 현재 프로젝트에서 앵커에 텍스트를 할당하고 클릭 방법을 첨부하여 특정 div의 가시성을 전환하는 세 가지 JS 기능 (현재 모든 글로벌)이있는 페이지가 있습니다. 아주 표준. 자바 스크립트를 네임 스페이스로 변환하고 함수를 호출

그래서 예를 들어 기능으로 기록됩니다

function toggleComments(){ 
    $("comments-section").hide(); 
    $("comments-button").click(function(){ 
     blah 
     return false; 
    }); 
} 

내가 네임 스페이스 이러한 기능을 누른 다음 다시 전화를 만들려면 어떻게해야합니까 내 질문은?

나는 다양한 예를 발견했지만 결정적인 것은 없습니다.

도움이 될 것입니다.

답변

1

빌리 달 좋은 출발을 보여 주지만, 객체 리터럴을 사용의 문제, 즉 당신이 할 수없는 상호 참조 다른 분야/기능/호텔입니다.

내가 많이 계시 모듈 패턴을 선호

를 누설하는 모듈 패턴은 내부 개인 기능/필드를 제공하기 위해 폐쇄의 자동 실행 기능 (종류의) 착취를 결합과 같은 작업을 수행 할 수 있습니다 (http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/ 참조) 매개 변수를 전달하여 네임 스페이스 객체를 초기화합니다.

var namespacedObject = function(param) { 

    var settings = param || someDefaultSetting, //default if no param supplied 
     somePrivateField = "someValue", 
     somePublicField = "i'm public"; 

    //define some method we will later make public 
    function toggleComments(){ 
     $("comments-section").hide(); 
     $("comments-button").click(function(){ 
      $(this).value= somePrivateField; 
      return false; 
     }); 
    } 

    //this is where the magic happens, 
    //return object with all public fields/functions 
    return { 
     toggleComments : toggleComments, 
     somePublicField : somePublicField 
    }; 

}(someParam); 

당신은 네임 스페이스 객체가 공개적으로 액세스 할 수있는 방법에서 참조 할 수있는 개인 필드 somePrivateField이 포함되어 있음을 볼 수 있습니다. 또한 공개 필드를 공개하고 함수 등에서 사용할 수있는/참조 할 수있는 매개 변수를 받아 들였습니다 (아무 것도 전달되지 않으면 기본값으로 설정할 수 있습니다)

은 다음과 같이 사용할 수 있습니다.

좋아요
namespacedObject.toggleComments(); 
alert(namespacedObject.somePublicField); 
alert(namespacedObject.somePrivateField); //undefined - it's private of course! 

이유 중 하나는 단지 도움이 자동 실행 기능

희망에서 반환 된 객체 리터럴에서이기는에 의해 공개/개인 무엇인지 보는 것은 매우 쉽다이다

2
// choos a namespace name that will not conflict with existing global variables 
var myNS = { 
     toggleComments: function(){ 
      $("comments-section").hide(); 
      $("comments-button").click(function(){ 
       // blah 
       return false; 
      }); 
     }, 
     anotherFunc: function(){ 
      return "something"; 
     } 
} 

// called like this 
myNS.toggleComments(); 
alert(myNS.anotherFunc()); 

또한 익명 자체 호출 함수에 코드를 포함해야합니다. 즉, 전역 네임 스페이스에 아무 것도 가질 수 없으므로 오염 위험이 없습니다.

// other peoples/modules code 
var myVariable = "whatever"; 

// anonymous function for your self contained code 
(function(){ 
var myVariable = "inside anonymous function"; 
alert(myVariable); 
})() // the empty brackets envoke the anonymous function 

// still retains value from before your self envoking anonymous function 
alert(myVariable); 
관련 문제