2012-04-12 3 views
0

이벤트 발생이 있으며 변수에 액세스하려고하는 함수의 내부에 있더라도 Uncaught TypeError: Cannot read property '...' of undefined이 표시됩니다. 그래서, 말하자면 :"this"유형의 JavaScript 변수에 다른 함수에서 액세스

나는 그것이 타이밍과 관련이 있다고 확신하지만 다시 잘못된 것일 수 있습니다. this 사본을 만들어 공개해야합니까? 누군가? 감사.

답변

3

this이 동적으로 값을 얻으므로 this의 값을 클로저에 고정 할 수 없습니다.

시도 :

var self = this; 

및 참조 자체. 당신이 $.fn.main에서 this를 사용하려면

+0

나는 단순함을 좋아하지만 모두 올바르게 해주었습니다. 감사. 확실히 나는 생각했다. –

+0

이것은 내가하는 일입니다. –

1

은 그냥 변수를 저장할 수 있습니다, 다른 변수

(function($) { 

    $.fn.main = function() { 

     this.setting = 1; 
     var that = this; 
     $("#someElement").scroll(function() { 

      console.debug(that.setting); 

     }); 

    } 

})(jQuery); 
0
(function($) { 

    $.fn.main = function() { 

     this.setting = 1; // "this" refers to the "$.fn.main" object 

     $("#someElement").scroll(function() { 

      console.debug(this.setting); // "this" refers to the "$('#someElement')" object 

     }); 

    } 

})(jQuery); 

this를 복사합니다. 다음은 작동합니다 다음 this 스크롤 내부 방법은 스크롤 방법에 refereing되어

(function($) { 

    $.fn.main = function() { 

     var that = this 

     that.setting = 1; // "this.setting" would also work 

     $("#someElement").scroll(function() { 

      console.debug(that.setting); // You need to reference to the other "this" 

     }); 

    } 

})(jQuery); 
0

. 이 메소드는 id 'someElement'요소의 scroll 이벤트에서 호출되도록 바인딩됩니다. 바인딩 오브젝트의 범위가 손실됩니다.

관련 문제