2011-09-23 4 views
0

안녕하세요 저는 싱글 톤 자바 스크립트 디자인 패턴을 사용하기 시작했지만 일부 범위 문제가 있습니다. 여기에 저는 작은 아약스로 실험하고 있습니다. 싱글 톤을 검색하고 저장합니다. 싱글 톤의 함수에서 다른 함수 (this.ready, Ajax가 데이터를 검색하고 저장할 때 호출 됨)가 있지만이 "singleton"을 참조하지 않고 "Object # XMLHttpRequest "크롬 디버거에 따르면 파이어 폭스는 정의되지 않았다고 말합니다. 내가 대신 전역 변수를 사용하는 상단에서 단일 변수로()을 getHTTPObject를 선언하려고하면"this"로 javascript singleton 범위 문제

  var mag = { 
       magObj: [], // object to store the retrieved json data 

       getData: function(){ 
        request = getHTTPObject(), // defined externally 
        request.onreadystatechange = this.setData; 
        request.open("POST", "be.php", true); 
        request.send(null); 
       }, 

       setData: function(){ 
        if (request.readyState == 4) 
        { 
         this.magObj = JSON.parse(request.responseText); 
         this.ready(); // this line yields the error, seems "this" does not refer to the singleton 

        } 
        else if (request.readyState == 1) 
        { 

        } 
       }, 

       ready: function() { 
        console.log('ready'); 
       }, 

       construct: function(){ 
        this.getData(); 
       }, 
      } 

또한 내가 정의되지 않은의 특성 'readyState가'를 읽을 수 없습니다 오류 를 얻을. 다시 것 같다 "이"getHTTPObject 내가 상단으로 설정에도 불구하고 정의되지 않은 수의 :

 var mag = { 
      magObj: [], 
      request: getHTTPObject(), 

      getData: function(){ 

       this.request.onreadystatechange = this.setData; 
       this.request.open("POST", "be.php", true); 
       this.request.send(null); 
      }, 

      setData: function(){ 
       if (this.request.readyState == 4) // debugger says this.request is undefined 
       { 
        this.magObj = JSON.parse(this.request.responseText); 

       } 
       else if (this.request.readyState == 1) 
       { 

       } 
      }, 

      construct: function(){ 
       this.getData(); 
      }, 
     } 
+1

자바 스크립트에서 "this"가 호출 함수에 따라 변경됩니다. 이 답변을 확인하십시오. http://stackoverflow.com/questions/4886632/what-does-var-that-this-mean-in-javascript – David

답변

1

당신이

  var mag = { 
      magObj: [], // object to store the retrieved json data 

      getData: function(){ 
       request = getHTTPObject(), // defined externally 
       request.onreadystatechange = this.setData; 
       request.open("POST", "be.php", true); 
       request.send(null); 
      }, 

      setData: function(){ 
       if (request.readyState == 4) 
       { 
        this.magObj = JSON.parse(request.responseText); 
        mag.ready(); // this line yields the error, seems "this" does not refer to the singleton 

       } 
       else if (request.readyState == 1) 
       { 

       } 
      }, 

      ready: function() { 
       console.log('ready'); 
      }, 

      construct: function(){ 
       this.getData(); 
      }, 
     } 
1

# 1
setDataXMLHttpRequest 개체에 대한 콜백 함수. 따라서 XMLHttpRequest 개체의 범위에서 실행됩니다. this 대신 mag을 사용하십시오.

# 2
동일 #1 같이 this 오히려 mag 변수보다는 XMLHttpRequest를 말합니다. 이 싱글 인 경우

1

가 범위의 문제를 해결하기 위해 시도 할 수, 당신은 자바 스크립트 폐쇄의 개념을 사용해야합니다. 기본적으로 범위 기능을 확인 좀 더 명확한 설명을 위해 .. 함수로 잡지 객체를 초기화하는 시도 .. 그 기능을 만들어 맥락에서 속성과 메서드에 액세스 할 수있는 곳 ..

var mag = function(){ 
    var magObj = []; 
    var getData = function(){ 
     //here you'll have access to the magObj collection 
    }; 
} 

이전의 고전이다 자바 스크립트 클로저의 예 .. 물론 mag 객체를 단순히 함수 호출로 인스턴스화합니다. mag();

희망이 도움이됩니다.