2012-11-14 2 views

답변

1

내부 setInterval this은 창을 나타냅니다. this을 참조하는 변수를 만들어야합니다.

object.waypoint=function() { 
    var me = this; 

    this.uw=setInterval(function() { 
     console.log(me); 
    }, 200); 
} 
+0

감사합니다! 나는 이미 그것을 시도했지만 "var"키워드를 삽입하지 않았다. 이것은 작동한다. :) –

+0

@ Otto-VilleLamminpää 질문에 대한 해결책을 찾은 경우 대답을 수락하십시오. – andlrc

1

일반적인 방법은 다음 적절한 this에 액세스하는데 사용할 수있는 것으로, 변수에 this에 대한 참조를 저장하는 것입니다 :

object.waypoint=function() { 
    // Keep a reference to this in a variable 
    var that = this; 
    that.uw=setInterval(function() { 
     // Now you can get access to this in here as well through the variable 
     console.log(that); 
    }, 200); 
} 
0

내가 bind 깔끔한 솔루션입니다 생각을 - 그것은 모든 브라우저에서 구현되지는 않지만 workarounds이 있습니다. 적절한 문서에 대한

object.waypoint = function(){ 
    this.uw = setInterval(function(){ 
     console.log(this); 
    }.bind(this), 200); 
} 

참조 MDN page

관련 문제