2011-02-07 9 views
0

다음 JavaScript 코드가 있습니다. 함수 업데이트에서 this.connection은 숫자 대신 undefined를 확인합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까? this을 사용하는 문제의this.connection의 JavaScript 범위 문제

function Net() 
{ 
    this.connection = -1;  
    this.counter = 1; 
    this.timelastsend = -1; 
    setInterval(this.update, 3000); 
} 

Net.prototype.update = function() 
{   
    if (this.connection > 0 && this.timelastsend > 0) 
    { 
     var now = new Date().valueOf();   
     if (now - this.timelastsend > 1000 * 60) 
     { 

     } 
    } 
} 
+0

this.timelastsend도 해결되지 않았습니다. – user535617

+0

어떻게 업데이트 기능을 호출합니까? – kjy112

+0

Net 개체를 어떻게 인스턴스화하고 업데이트 함수를 호출합니까? 이것이 제대로 수행되면 볼 수있는만큼 많이 작동합니다. – Christian

답변

6

하나는 this 당신이 함수를 호출하는 방식에 의존한다는 것이다.

setIntervalupdate 메서드를 독립 실행 형 함수처럼 호출하므로 this이 전역 개체로 설정됩니다.

당신이 정말로 this 기능을 사용해야하는 경우 다음과 같이하여 setInterval에에 전화를 다시 작성 :

function Net() { 
    var self = this; 
    this.connection = -1;  
    this.counter = 1; 
    this.timelastsend = -1; 
    setInterval(function() { self.update() }, 3000); 
} 

이 방법, 당신이 당신의 객체를 참조 유지하는 self 변수를 만듭니다 (경우new 연산자를 사용하여 생성했습니다. this을 피하기위한 또 다른 이유입니다.


부록 :

더를
function createNet() { 
    var connection = -1, 
     counter = -1, 
     timelastsent = -1, 
     self, 
     update; 

    update = function() { 
     var now; 
     if (connection > 0 && timelastsent > 0) { 
      now = new Date().valueOf(); 
      if (now - timelastsent > 1000 * 60) { 

       // ... update code ... 

       counter += 1; 
       timelastsent = now; 
      } 
     } 
    }; 

    setInterval(update, 3000); 

    return { 
     update: update, 
     getTimeLastSent: function() { return timelastsent; }, 
     getCounter: function() { return counter; }, 
     getConnection: function() { return connection; } 
    }; 
} 
당신은 알 수

있다 : 당신이 적극적으로 인터넷 pseudoclass에서 개체를 많이 하강하지 않는 경우 다음 없기 때문에가 , 내가 일을 리팩토링 것 어디서나 this에 대한 언급은 모호성을 의미하지 않습니다. 연결, 카운터, 타임 스팟 프로퍼티에 3 개의 getter를 포함 시켰습니다.하지만 객체 외부에서 쓰기가 가능하도록하려면 생성 된 객체에 쉽게 추가 할 수 있습니다.